php - 交换字符串php中的两个单词

标签 php str-replace

假设有一个字符串“foo boo foo boo”我想用boo替换所有fooes,用foo替换所有booes。预期输出为“boo foo boo foo”。我得到的是“foo foo foo foo”。如何获得预期输出而不是当前输出?

    $a = "foo boo foo boo";
    echo "$a\n";
    $b = str_replace(array("foo", "boo"), array("boo", "foo"), $a);
    echo "$b\n";
    //expected: "boo foo boo foo"
   //outputs "foo foo foo foo"

最佳答案

使用strtr

来自手册:

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

In this case, the keys and the values may have any length, provided that there is no empty key; additionaly, the length of the return value may differ from that of str. However, this function will be the most efficient when all the keys have the same size.

$a = "foo boo foo boo";
echo "$a\n";
$b = strtr($a, array("foo"=>"boo", "boo"=>"foo"));
echo "$b\n"; 

输出

foo boo foo boo
boo foo boo foo

In Action

关于php - 交换字符串php中的两个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17850603/

相关文章:

php - 如何在 CakePHP 查找查询中正确嵌套自定义字段?

c# - 如何从字符串中去掉反斜杠 ("\") 字符

javascript - ReplaceAll 以清理字符串

regex - 删除第二个逗号之前的文本 ('' ,") 字符串替换模式

php - Swiftmailer:按用户 ID 进行 dbReplacements?

javascript - Onclick链接保存多个数据无需刷新

php - CKEditor 图像无法正常工作

PHP Utf8 MySQL_查询、JSON_编码

php - 如何将 [link](#) 替换为 <a href ="#">link</a>?

Java 字符串替换