phpreplacestr-replacestrtr

strtr is replacing in an unexpected way


strtr is replacing in an unexpected way. Please take a look at my code.

$stringX = "Do you remember me?";

strtr($stringX, array("you" => "me", "me" => "you"));

Expected output: Do me remember you.

Actual output: Do me reyoumber you.

How do I get the expected output?


Solution

  • Try this:

    $stringX = "Do you remember me?";
    
    strtr($stringX, array("you" => "me", " me" => " you"));
    

    Note the space before me!!!

    NOTE: This will work only in this specific case and might produce unexpected output for other strings!