我在 PHP 中有一个字符串。我想用另一个字符的值交换某个字符。如果我按照我的方式去做,A 变成 B 将用 B 替换 A,但已经存在的 B 值将保持不变。当我尝试将 B 交换为 A 时,当然,有些值最初并未交换,因为它们已经存在了。
我试过这个代码。
$hex = "long_hex_string_not_included_here";
$hex = str_replace($a,$b,$hex);
//using this later will produced unwanted extra swaps
$hex = str_replace($b,$a,$hex);
我正在寻找一个函数来交换这些值。
最佳答案
只需使用 strtr
.这就是它的设计目的:
$string = "abcbca";
echo strtr($string, array('a' => 'b', 'b' => 'a'));
输出:
bacacb
在这里有帮助的关键功能是当
strtr
以两个参数形式调用:Once a substring has been replaced, its new value will not be searched again.
这就是阻止
a
的原因被 b
取代然后被 a
取代再次。Demo on 3v4l.org
关于php - 如何用 PHP 交换字符串中两个不同字符的值? A变成B,B变成A,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54073183/