str_replace with array

LautaroAngelico picture LautaroAngelico · Dec 5, 2012 · Viewed 148.3k times · Source

I'm having some troubles with the PHP function str_replace when using arrays.

I have this message:

$message = strtolower("L rzzo rwldd ty esp mtdsza'd szdepw ty esp opgtw'd dple");

And I am trying to use str_replace like this:

$new_message = str_replace(
    array('l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','b','c','d','e','f','g','h','i','j','k'),
    array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'),
    $message);

The result should be A good glass in the bishop's hostel in the devil's seat, but instead, I get p voos vlpss xn twt qxswop's wosttl xn twt stvxl's stpt.

However, when I only try replacing 2 letters it replaces them well:

$new_message = str_replace(array('l','p'), array('a','e'), $message);

the letters l and p will be replaced by a and e.

Why is it not working with the full alphabet array if they are both exactly the same size?

Answer

Rakesh Tembhurne picture Rakesh Tembhurne · Dec 5, 2012

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

    // Outputs F because A is replaced with B, then B is replaced with C, and so on...
    // Finally E is replaced with F, because of left to right replacements.
    $search  = array('A', 'B', 'C', 'D', 'E');
    $replace = array('B', 'C', 'D', 'E', 'F');
    $subject = 'A';
    echo str_replace($search, $replace, $subject);