phpstrtr

Replace two words with each other simultaneously


I need to replace the word 'me' with the word 'you', and the word 'you' with the 'me' simultaneously. It works with strtr() when the 2 words aren't next to each other, but when they are, it replaces the first word, then ignores the second word. Is there any way to fix this?

<?php

$string = "tell me you want to get it right";
$string = trim(strtr(" ".trim($string)." ", array(
" me " => " you ",
" you " => " me "
)));

echo $string;

?>

Actual Result:

tell you you want to get it right

Need Result:

tell you me want to get it right

PS: Don't really want any answers that uses something like "Replace all 'you's with 'you1234', and then all 'me's with 'me1234', then just replace all 'you1234's with 'me', and all 'me1234's with 'you'.


Solution

  • How about using an anonymous function with an array? Any excuse to use an anonymous function, makes me happy :)

    $string = "tell me you want to get it right";
    $string = implode(" ", array_map(function($word, $swap = ["me", "you"]) {
        return ($index = array_search($word, $swap)) === false
            ? $word : $swap[++$index % 2];
    }, explode(" ", $string)));
    var_dump($string);
    /* string 'tell you me want to get it right' (length=32) */
    

    Or for more complicated replacements

    $string = "tell me you want to get it right";
    $replacements = ["me" => "you", "you" => "me", "right" => "wrong"];
    $string = implode(" ", array_map(function($word) use($replacements) {
        return isset($replacements[$word]) ? $replacements[$word] : $word;
    }, explode(" ", $string)));
    var_dump($string);
    /* string 'tell you me want to get it wrong' (length=32) */