I have set up a very simple code snippet:
$string = 'Some random words. Some more random, very random words.';
$words = explode(" ", $string);
for ($i = 0; $i < count($words); $i++) {
$word = $words[$i];
$words[$i] = str_replace(".", "!", $word);
$words[$i] = str_replace(",", "?", $word);
}
print_r($words);
The output is this:
Array
(
[0] => Some
[1] => random
[2] => words.
[3] => Some
[4] => more
[5] => random?
[6] => very
[7] => random
[8] => words.
)
Why only the second str_replace() function affect the string? If I remove the second str_replace() the first one works perfectly. It’s not about usage of str_replace() but I believe me doing something very very simply wrong.
By the way – I am aware of preg_replace() and passing an array to str_replace() but would like to hear about this particular situation :).
EDIT:
Thank you all for blazing quick responses. I am in a shame for such an issue but it really didn’t catch my eyes at first. Thanks everyone! I will accept the first correct answer by Mike Brant.
It is because your second statement uses
$wordas the subject of replacement and not$words[$i]which was where you assigned the string after the first replacement.You can fix by either working directly with
$words[$i]the entire time, or working exclusively with your temp variable and then making assignment like this: