6

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?

4 Answers 4

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

gives:

PHP does my head in!

See the docs for the modifier 'e'.

Sign up to request clarification or add additional context in comments.

2 Comments

The 'e' modifier is "deprecated and use is highly discouraged" since PHP 5.5. according to the docs cited in this answer. An alternative solution using preg_replace_callback() is presented here
And the 'e' modifier is REMOVED as of PHP 7.0.0.
3

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

Comments

2

You could use the eval modifier...

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

Comments

1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.