0

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?

vascowhite
  • 18,120
  • 9
  • 61
  • 77
xaxaxa
  • 23
  • 1

3 Answers3

4

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:

  1. 1 is replaced with do 25 lat
  2. In that string, 2 is replaced with od 26 do 35 lat, giving you do od 26 do 35 lat5 lat
  3. In that string, 3 is replaced with pow. 35 r.z. giving you the final result you're seeing.
Aleks G
  • 56,435
  • 29
  • 168
  • 265
1

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;
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

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"
Bart Platak
  • 4,387
  • 5
  • 27
  • 47