views:

61

answers:

2

How do I address special characters in Regex? @ ? # $ % %...
this patten searches for a letter that comes between a prefix and a suffix.

$pattern = '/((?<!\b$PREFIX)$LETTER|$LETTER(?!$SUFFIX\b))/i';

$string = 'end'; 

$prefix = 'e';  
$letter = 'n';  
$suffix = 'd';  

But what if $string began with a #

$string = '#end';
$prefix = ???

edit: This is the preg_replace in full

$text = "<p>Newton, Einsteing and Edison. #end</p>"
$pattern = '/((?<!\b$PREFIX)$LETTER|$LETTER(?!$SUFFIX\b))/i';
echo preg_replace($pattern, '<b>\1</b>', $text);

this replaces all the n letters with a bold n but is supposed to exculde the n in #end

+1  A: 

You have to escape the special chars first with a backslash. But as the backslash already escape letters in a string, you'll have to escape your backslash first.

$string = '\\#end';

A better way to do this is to use the preg_quote() function on your string, and specify what kind of delimiter you use (here "/").

preg_quote($string, '/');
Colin Hebert
@Colin Hebert, Thanks!
dany
+2  A: 

You have to enclose your pattern with double quote to make the variables interpolated.

$pattern = "/((?<!\b$PREFIX)$LETTER|$LETTER(?!$SUFFIX\b))/i";

And more, you define $prefix (lower case) and use $PREFIX (uppercase). So the script becomes the following and works fine for me :

<?php
$PREFIX = 'e';  
$LETTER = 'n';  
$SUFFIX = 'd';  
$text = "<p>Newton, Einsteing and Edison. #end</p>";
$pattern = "/((?<!\b$PREFIX)$LETTER|$LETTER(?!$SUFFIX\b))/i";
echo preg_replace($pattern, "<b>$1</b>", $text),"\n";
?>

Output:

<p><b>N</b>ewto<b>n</b>, Ei<b>n</b>stei<b>n</b>g a<b>n</b>d Ediso<b>n</b>. #end</p>

without code formating:

Newton, Einsteing and Edison. #end

M42
@M42, thank you very much!
dany