如何用 PHP 交换字符串中两个不同字符的值?A变成B,B变成A [英] How can I swap the values of two different characters in a string with PHP? A becomes B, B becomes A

查看:79
本文介绍了如何用 PHP 交换字符串中两个不同字符的值?A变成B,B变成A的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PHP 中有一个字符串.我想用另一个字符的值交换某个字符.如果我按照我的方式去做,A 变成 B 将用 B 替换 A,但已经存在的 B 值将保持不变.当我尝试将 B 交换为 A 时,当然,有些值最初并未交换,因为它们已经存在了.

I have a string in PHP. I want to swap a certain character with the value from another character. If I do it my way, A becoming B will replace A with B but the already existing B values will remain the same. When I try to swap B into A, there are, of course, values that were not originally swapped, because they were already there.

我试过这个代码.

$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);

我正在寻找一个函数来交换这些值.

I am looking for a function to swap these values.

推荐答案

只需使用 strtr.这就是它的设计目的:

Just use strtr. It's what it was designed for:

$string = "abcbca";
echo strtr($string, array('a' => 'b', 'b' => 'a'));

输出:

bacacb

在这里有帮助的关键功能是当 strtr 以两个参数的形式被调用时:

The key functionality that helps here is that when strtr is called in the two argument form:

一旦子字符串被替换,它的新值将不会被再次搜索.

Once a substring has been replaced, its new value will not be searched again.

这就是阻止 ab 替换然后再次被 a 替换的原因.

This is what stops the a that was replaced by b then being replaced by a again.

3v4l.org 上的演示

这篇关于如何用 PHP 交换字符串中两个不同字符的值?A变成B,B变成A的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆