开发者

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.

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 开发者_如何学Cmy 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

$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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜