Nesting preg_replace functions while escaping tokens
I'm using the 'e' modifier in preg_replace to search for a given string. Then I need it to look within that string for individual matches using another preg_replace statement:
$str = "This is FOO.";
$str = preg_replace('/(foo)/ie', "x$1", $str);
echo $str;
This will generate: This is xFOO.
$str = "This is FOO.";
$str = preg_replace('/(foo)/ie', "preg_replace('/(\w)/i','x$1','$1')", $str);
echo $str;
I need this to generate This is xFxOxO.
This is xFOOxFOOxFOO.
When php evaluates the second line of code, it's replacing both $1 tokens with the matched string foo
. I need it to ignore the first $1 token because that is supposed to be evaluated by the inner preg_replace statement. How can I escape the first $1 token so that it won't be evaluated by the outside preg_replace statement?
you can trick the parser with something like
$str = preg_replace('/(foo)/ie', "preg_replace('/(\w)/i','x$'.'1','$1')", $str);
but, honestly, it looks totally ugly. You might want to tell us more about the problem, i'm sure there are better ways.
精彩评论