PHP preg_replace - search for replacements from an array using matching as a key

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?

+6
php regex preg-replace
source share
4 answers
 echo preg_replace('/%([a-z_]+)%/e', '$rep["$1"]', $str); 

gives:

  PHP does my head in!

See documents for modifier 'e' .

+7
source share

You can use the eval modifier ...

 $res = preg_replace('/\%([a-z_]+)\%/e', "\$rep['$1']", $str); 
+2
source share

The "e" modifier seems to be out of date. There are security issues. Alternatively, you can use preg_replace_callback.

 $res = preg_replace_callback('/\%([a-z_]+)\%/', function($match) use ($rep) { return $rep[$match[1]]; }, $str ); 
+2
source share

Just to provide an alternative to preg_replace ():

 $str = "PHP %foo% my %bar% in!"; $rep = array( 'foo' => 'does', 'bar' => 'head' ); function maskit($val) { return '%'.$val.'%'; } $result = str_replace(array_map('maskit',array_keys($rep)),array_values($rep),$str); echo $result; 
+1
source share

All Articles