gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:36:43 25 4
gpt4 key购买 nike

假设有一个字符串“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com