I have a string which can contain multiple matches (any word surrounded by percentage marks) and an array of replacements - they key of each replacement being the match of the regex. Some code will probably explain that better...
$str = "PHP %foo% my %bar% in!";
$rep = array(
'foo' => 'does',
'bar' => 'head'
);
The desired result being:
$str = "PHP does my head in!"
I have tried the following, none of which work:
$res = preg_replace('/\%([a-z_]+)\%/', $rep[$1], $str);
$res = preg_replace('/\%([a-z_]+)\%/', $rep['$1'], $str);
$res = preg_replace('/\%([a-z_]+)\%/', $rep[\1], $str);
$res = preg_replace('/\%([a-z_]+)\%/', $rep['\1'], $str);
Thus I turn to Stack Overflow for help. Any takers?