同时替换所有单词

时间:2016-03-23 02:41:27

标签: php preg-replace

我尝试使用str_replace()同时替换所有单词,但我不知道该怎么做。基本上,我需要同时将you更改为me,将me更改为you。我该怎么做?

<?php

$string = "you me";
$string = str_replace("you", "me", $string);
$string = str_replace("me", "you", $string);

echo $string;

?>

结果:

you you

需要结果:

me you

1 个答案:

答案 0 :(得分:1)

strtr()可以接受数组'from' => 'to'替换为第二个参数:

echo strtr($string, array('you' => 'me', 'me' => 'you'));