Reham Fahmy
Reham Fahmy

Reputation: 5063

unexpected behaviour of str_replace with array

I've the following function and using str_replace gives an unexpected result

function repo($text) {
    $search = array("0","1","2","3","4","5","6","7","8","9");
    $replace = array("z30","z31","z32","z33","z34","z35","z36","z37","z38","z99");
    $text = str_replace($search,$replace,$text);
    return $text;
}

echo repo('0');

The expected answer is

z30

and instead I get

zz330

What am I doing wrong?

Upvotes: 0

Views: 128

Answers (2)

Atze Kaputtnik
Atze Kaputtnik

Reputation: 272

Just like the documentation says:

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.

You probably want to do something like this instead:

function repo($text){
    $search = array("0","1","2","3","4","5","6","7","8","9");
    $replace = array("z30","z31","z32","z33","z34","z35","z36","z37","z38","z99");
    $replacePairs = array_combine($search, $replace);
    return strtr($text, $replacePairs);
}

Upvotes: 2

Vahe Shadunts
Vahe Shadunts

Reputation: 1966

Your function works this way.

0 changes to z30, php continues loop the arrays, then z30 contains '3', and 3 changes to z33. Because of that returns 'z' + 'z33' + '0' = zz330.

Upvotes: 5

Related Questions