2
votes

I'm currently using PHP's str_replace to replace a particular value with another, in a loop.

The problem is, str_replace will replace ALL of the instances of the first value, with the second value, rather than replacing them sequentially. For example:

$replacements = array('A', 'one', 'some');
$str = "The quick brown fox jumps over the lazy dog and runs to the forest.";
foreach($replacements as $replace){
    $str = str_replace('the', $replace, $str);
}

this will ultimately return:

"A quick brown fox jumps over A lazy dog and runs to A forest."

rather than what I want which would be:

"A quick brown fox jumps over one lazy dog and runs to some forest."

What would be the most efficient way of doing this? I thought I could use preg_replace but I'm mediocre with regex.

3
Similar but definitely not duplicates... that one wants to limit to only one replace total, I want to do a sequential replace of each instance of needle, with a different replacement value.JVC

3 Answers

6
votes

Untested, but I think this will do the trick.

$replacements = array('A', 'one', 'some');
$str = "The quick brown fox jumps over the lazy dog and runs to the forest.";
foreach($replacements as $replace){
    $str = preg_replace('/the/i', $replace, $str, 1);
}
echo $str;

Edit: added the i to make it case insensitive

0
votes

Okay maybe this is super convoluted?

$replacements = array('A', 'one', 'some');
$str = "The quick brown fox jumps over the lazy dog and runs to the forest.";
$str_array = explode(" ", $str);
$replace_word = "the";
$i = $j = 0;
foreach($str_array as $word){
      if(strtolower($word) === $replace_word){
         $str_array[$i] = $new_word[$j];
         $j++;
      }
   $i++;
}
$str = implode(" ", $str_array);
-2
votes

Apparantly this seemed to work :

$replacements = array('A', 'one', 'some');
$the=array('the','the','the');
$str = "The quick brown fox jumps over the lazy dog and runs to the forest.";
$str = str_ireplace($the, $replacements, $str);

I think this is exactly what was asked.

see parameter description http://php.net/manual/en/function.str-replace.php

http://codepad.org/VIacFmoM