0

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.