Reputation: 25535
I want to use preg_replace
with one pattern and an array of replacements that are all different. In other words, for each occurrence of the match I want to iterate down the replacements array for a replacement.
Is there any way to do this?
I tried using preg_replace_callback
- the callback accepts an array of matches but has to only return one string- no way to tell which match you are replacing.
I also tried using the count
param and passing it the callback function - it's 0 every time and after the preg_replace is done it and thentells the total number of matches.
Upvotes: 0
Views: 2027
Reputation: 89584
You don't need to iterate, if you create an array of patterns with the same size as your array of replacements, example:
$string = 'obo oto oko';
$pattern = '~o.o~i';
$replacements = array('glip', 'glap', 'glop');
$patterns = array_fill(0, count($replacements), $pattern);
$result = preg_replace($patterns, $replacements, $string, 1);
print_r($result);
Upvotes: 0
Reputation: 1385
Taking @Andreas' answer and improving it a bit for performance:
$count = 1;
foreach ($replaceArray as $replace)
{
preg_replace($pattern, $replace, $subject, 1, $count);
if ($count == 0)
break;
}
This will check whether a replacement has been performed, and if that's not the case (as there's no more match), the loop is abandoned. This will save performance in case there are more elements in $replaceArray
than matches in $subject
.
Upvotes: 2
Reputation: 2678
Try something along the lines:
foreach ($replaceArray as $replace)
{
$subject = preg_replace($pattern, $replace, $subject, 1);
}
It will loop through you replacement array and replaces only 1 at a time.
Upvotes: 1