3

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.

1
  • 1
    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. Commented Oct 20, 2011 at 1:40

3 Answers 3

7

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

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

8 Comments

+1. Works when I run it here: codepad.org/Sxpksp0A -- I suppose a more efficient method might be to use a single call to preg_replace_callback()...
hmmm works on codepad but not working for me in production. Here is my real line of code: $to_parse = preg_replace('/{{'.$words.'}}/i', $output, $to_parse, 1); I'm replacing a series of tokens in the format {{value}}, does the pattern need tweaking to find that? I tried escaping the braces but it didn't seem to help...
Here is a stripped down version of my production code on codepad... what's odd is the initial preg_match_all is throwing an error when that part works fine for me in production. codepad.org/zxhRKLUx
Get it working with a static test string and no curly braces first. Then add your curly braces and get that working. Then add your $words variable.
I think you need to escape the | characters when you use them in your pattern. I made untested adjustments here: codepad.org/XMgUJeZO
|
0

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 Comments

Yes I just noticed that typo actually but SE won't allow me to edit it. In my production code, that mistake is not present.
Yeah that's very similar to the approach I took to work around this... I just figured there HAD to be a better way than blowing up multiple paragraphs of content into individual words and doing a comparison on every word.
-2

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

8 Comments

Thanks, I was not aware of the 'count' feature of str_replace! Unfortunately it does not appear to be doing anything at all. There is no change to my results. Additionally when I use an integer for the number rather than a variable, I get Fatal error: Only variables can be passed by reference
The "count" parameter is a reference to a variable in which str_replace() will write the number of replacements made. It has nothing to do with what the OP asked.
aha, that explains why it didn't seem to do what I thought it would, based on the suggestion to use it!
That's not how the $count parameter works. You supply a variable for $count, and after the operation is performed $count will tell you how many replacements were made.
I edited my answer, we need not go through a loop when we have array of search elements and another array of replace elements, the function does it itself.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.