I have a string that can contain several matches (any word surrounded by percentage marks) and an array of replacements - the key of each replacement matches the regular expression. Some code will probably explain which is better ...
$str = "PHP %foo% my %bar% in!"; $rep = array( 'foo' => 'does', 'bar' => 'head' );
Desired Result:
$str = "PHP does my head in!"
I 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);
So, I turn to qaru for help. Any members?
php regex preg-replace
aaronrussell
source share