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?
Pass the
/eflag.A safer alternative is to use
preg_replace_callback.