开发者

PHP preg_replace - finding the replacement from an array using the match as the key

开发者 https://www.devze.com 2023-01-07 03:52 出处:网络
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 pr

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开发者_Go百科...

$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?


echo preg_replace('/%([a-z_]+)%/e', '$rep["$1"]', $str);

gives:

PHP does my head in!

See the docs for the modifier 'e'.


It seems that the modifier "e" is deprecated. There are security issues. Alternatively, you can use the preg_replace_callback.

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


You could use the eval modifier...

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


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消