I wrote this code:
<?
$text='how are you [b] today [/b]';
$patterns = array();
$patterns[0] = '/\[b/';
$patterns[1] = '/\b]/';
$replacements = array();
$replacements[1] = 'b]aaa<>';
$replacements[0] = '<>aaa[b';
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $text);
echo "_";
echo $text;
echo "_";
echo "END";
?>
the output shows:
how are you <>aaa[bb]aaa<> today [/b]aaa<>______how are you [b] today [/b]______END
but the output should be:
how are you <>aaa[b] today [/b]aaa<>______how are you [b] today [/b]______END
what did I do wrong? Please help. Thank you
You need to double-escape the brackets:
A single backslash will be “consumed” by PHP when it parses the string, leaving just a bare
[, which will be seen by the regex engine as the beginning of a character class. By double-escaping, the\\will be seen by PHP as an escape, leaving a single\, which will be seen by the regex engine as an escape.