I have a single regex and I want to replace each match in the array of matches with a corresponding array of replacements in the most efficient way possible.
So for instance, I have:
$string = '~~hello~~ there, how ~~are~~ ~~you~~?';
$pattern = '/~~(.*?)~~/';
$replacements = array();
$replacements[0] = 'hi';
$replacements[1] = 'am';
$replacements[2] = 'i';
and I want to turn $string
into:
hi there, how am i?
Initially I hoped it'd be as simple as:
$string = preg_replace($pattern, $replacements, $string);
but it doesn't seem to work. So the first question is: if $replacements
is an array, then does $string
must also be an array?
Now, I can come up with (seemingly) inefficient ways to do this, like counting the number of matches and making an array filled with the appropriate number of identical regexes. But this leads us into question two: is there a more efficient way? How would you do it, PHP pros?