views:

23

answers:

1

Suppose I want to replace occurrences of "foo" with "oof":

$s = "abc foo bar";
echo preg_replace('/(foo)/', strrev("$1"), $s);

Instead of "abc oof bar" I get "abc 1$ bar". In other words, it's passing the literal string "$1" to the strrev() function, instead of the regex match, "foo".

What's the best way to fix this problem in the above code?

+2  A: 

Pass the /e flag.

echo preg_replace('/(foo)/e', 'strrev("\\1")', $s);

A safer alternative is to use preg_replace_callback.

function revMatch ($matches) {
  return strrev($matches[1]);
}
...

echo preg_replace_callback('/(foo)/', "revMatch", $s);
KennyTM