I'm running simple PHP code
$myVariable = 1;
$myVariable2 = str_replace(array(1, 2, 3), array('do 25 lat', 'od 26 do 35 lat', 'pow. 35 r.z.'), $myVariable);
echo $myVariable2;
And result is:
do od 26 do pow. 35 r.z.5 lat5 lat
I checked on different PHP versions. Any ideas?
You're falling victim to the gotcha specified in the documentation - look under "notes" on the str_replace
documentation
Replacement order gotcha
Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.
Essentially what's happening is the sequential replacements, as you passed an array as the second parameter:
This is because str_replace
array pairs are applied one after the other.
Try strtr
:
$myVariable = 1;
$replacePairs = array(
1 => "do 25 lat",
2 => "od 26 do 35 lat",
3 => "pow. 35 r.z."
);
$myVariable2 = strtr($myVariable,$replacePairs);
echo $myVariable2;
It's not a bug, this is the normal behavior of str_replace
. What happens is the function iterates through your search
array and each time it finds an occurrence, it replaces it with relevant replace
.
Thus:
(search and match 1) 1 -> "do 25 lat"
(search and match 2) "do 25 lat" -> "do od 26 do 35 lat5 lat"
(search and match 3) "do od 26 do 35 lat5 lat" -> "do od 26 do pow. 35 r.z.5 lat5 lat"