我需要用“你”这个词替换“我”这个词,同时用“我”代替“你”这个词。 当两个单词不是彼此相邻时,它与strtr()一起使用,但是当它们相同时,它将替换第一个单词,然后忽略第二个单词。 有没有什么办法解决这一问题?
<?php $string = "tell me you want to get it right"; $string = trim(strtr(" ".trim($string)." ", array( " me " => " you ", " you " => " me " ))); echo $string; ?>实际结果:
告诉你你想要做对
需要结果:
告诉你我想要做对
PS:不要真的想要任何使用类似“将所有'替换为'you1234',然后所有'我用'me1234'的答案,然后将'you1234'替换为'me',并将所有'me1234'替换为''您'。
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'.
最满意答案
如何使用带数组的匿名函数? 任何使用匿名函数的借口都让我开心:)
$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) */或者更复杂的替代品
$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) */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) */更多推荐
发布评论