Organizational Research By

Surprising Reserch Topic

preg replace with array replacements using -'php,regex,string'

preg replace with array replacements  using -'php,regex,string'

$string = ":abc and :def have apples.";
$replacements = array('Mary', 'Jane');

should become:

Mary and Jane have apples.

Right now I'm doing it like this:

preg_match_all('/:(\w+)/', $string, $matches);

foreach($matches[0] as $index => $match)
   $string = str_replace($match, $replacements[$index], $string);

Can I do this in a single run, using something like preg_replace?

asked Sep 7, 2015 by rajesh
0 votes

Related Hot Questions

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.