phppreg-replacestrtr

Using strtr inside a preg_replace?


I'd like to reformat a preg_replace() match with strtr() inside the preg_replace. Is it possible ?

I did the following:

$array = array("#" => "_", "/" => "-");
$output = preg_replace($regex, '<span>'.strtr('$0', $array).'</span>', $input);

In my example Z# (which corresponds to my preg_replace match, $0 in the strtr) should become Z_, but nothing happens.

Thank you !

nb. $regex is a regular expression matching some portions of $input, it works.


Solution

  • Use the e-modifier:

    $output = preg_replace('/$regex/e', '"<span>".strtr("$0", $array)."</span>"', $input);