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
7 views



Related Hot Questions



Government Jobs Opening


...