0

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.

3 Answers 3

2

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.

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

1 Comment

I didn't downvote, but actually, I don't need those extra lines of code because in my particular case there will always be the same number of items in the replacement array as what I'm replacing.
1

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.

Comments

0

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

2 Comments

I do need to iterate though, and I tried just that. Problem is I'm replacing the strings with strings that match the pattern. So for each item in the array, preg_replace goes back through the whole string and replaces the replacements.
@inorganik: Can you edit your post and write an example of input, patterns and desired output?

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.