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.
Now I need to nest. (I’m nesting because I need to match an unknown number of groups into separate tokens which is not possible with a single preg_replace statement as discussed elsewhere on this forum. I’ve obviously simplified this code to focus on my question).
$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.
But instead it generates 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
but, honestly, it looks totally ugly. You might want to tell us more about the problem, i’m sure there are better ways.