tags:

views:

25

answers:

1

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?

+1  A: 

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.

stereofrog
Yes, that worked nicely. Just adding that `'.'` was enough to delay the evaluation of that token. Thank you. To answer your question, i'm using this to markup a text file into xml. I was identifying a whole row with <row> tags, then identifying elements within it with <heading> tags.
Andrew
i'd suggest preg_replace_callback for this.
stereofrog