同时替换两个单词

Replace two words with each other simultaneously

我需要同时用 'you' 替换 'me' 和 'me' 替换 'you'。当两个单词不相邻时,它与 strtr() 一起使用,但当它们相邻时,它会替换第一个单词,然后忽略第二个单词。有什么办法可以解决这个问题吗?

<?php

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

echo $string;

?>

实际结果:

告诉你你想做对

需要结果:

告诉你我想做对

PS: 真的不想要任何使用类似“将所有 'you' 替换为 'you1234' 之类的答案,然后将所有 'me' 替换为 'me1234',然后将所有 'you1234' 替换为 'me',并将所有 'me1234' 替换为 'you'.

这似乎可行,无论单词是连续的还是分开的。

$str = "foo something bar";
echo preg_replace_callback(
    '/\b(foo|bar)\b/',
    function($match) { return $match[0] == 'foo' ? 'bar' : 'foo'; },
    $str
);

不是真的同时;回调循环遍历匹配项。然而,替换似乎是在原始字符串上完成的,而不是在每次回调后更新的临时字符串(避免你的 "you you" 示例),所以它基本上是一样的。

这有点(在某种程度上,因为使用了廉价的技巧)

Replace all 'you's with 'you1234', and then all 'me's with 'me1234'

answer...但是,它应该有效。它是函数,字符串和替换(关联)数组是参数。它应该同时适用于多个替换。字符串的位置无关紧要。

function replace_sim($str, $replace) {

  $arr = str_word_count($str, 1);
  $keys = array();
  $real_val = array();
  for ($i = 0; $i < count($arr); $i++) {

    foreach($replace as $key => $value) {
      if ($arr[$i] == $key) {
        $arr[$i] = strrev($value);

        $keys[] = $i;
        $real_val[] = $value;
      }
    }

  }
  $i = -1;
  foreach($keys as $key) {
    $i++;
    $arr[$key] = $real_val[$i];
  }

  $str = join(' ', $arr);
  return $str;
}

//usage
$string = "tell me you want to you get it right me you";
$replace=array('me'=>'you','you'=>'me','get'=>'it','it'=>'get');
echo replace_sim($string,$replace);

echo '<br>';

$string = "tell me i want you";
$replace=array('me'=>'you','you'=>'me');
echo replace_sim($string,$replace);

对数组使用匿名函数怎么样?任何使用匿名函数的借口,都让我高兴:)

$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) */