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 $word
as 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:
for ($i = 0; $i < count($words); $i++) {
$word = $words[$i];
$word = str_replace(".", "!", $word);
$words[$i] = str_replace(",", "?", $word);
}
Because you were applying str_replace
to the same string over and over again. You need to reassign the new string (with replaced characters) and perform another replace on the updated value
for ($i = 0; $i < count($words); $i++) {
$word = $words[$i]; //initial value
$word = str_replace(".", "!", $word); //change $word to modified text
$word = str_replace(",", "?", $word); //change $word to modified text
$words[$i] = $word;
}
The $word
value doesn't get changed by str_replace
, so it remains the same. To change it, you need to assign the return value/result from str_replace
Change to:
for ($i = 0; $i < count($words); $i++) {
$words[$i] = str_replace(".", "!", $words[$i]);
$words[$i] = str_replace(",", "?", $words[$i]);
}
Even shorter:
for ($i = 0; $i < count($words); $i++) {
$words[$i] = str_replace(array(".", ","), array("!", "?"), $words[$i]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.