繁体   English   中英

如何使用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

我在PHP中有一个字符串。 我想将某个字符与另一个字符的值交换。 如果我按照自己的方式做,那么成为B的A将用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时:

替换子字符串后,将不再搜索其新值。

这是停止a被替换由b然后被替换a试。

3v4l.org上的演示

我们可以尝试用B第三个中间值替换,然后将所有A替换为B ,然后将标记替换回A 但是,这始终使标记字符可能已经出现在字符串中的某个位置成为可能。

一种更安全的方法是将输入字符串隐藏为一个字符数组,然后仅检查每个索引中的AB并沿着该数组向下走,然后进行相应的交换。

$input = "AzzzzB";
echo $input ."\n";
$arr = str_split($input);

for ($i=0; $i < count($arr); $i++) {
    if ($arr[$i] == 'A') {
        $arr[$i] = 'B';
    }
    else if ($arr[$i] == 'B') {
        $arr[$i] = 'A';
    }
}
$output = implode('', $arr);
echo $ouput;

AzzzzB
BzzzzA

还要注意,这种方法是有效的,只需要向下遍历输入字符串一次即可。

使用Temp值(在字符串中不会出现。可以是任何值):

$temp = "_";
$a = "a";
$b = "b";
$hex = "abcdabcd";
$hex = str_replace($a,    $temp, $hex); // "_bcd_bcd"
$hex = str_replace($b,    $a,    $hex); // "_acd_acd"
$hex = str_replace($temp, $a,    $hex); // "bacdbacd"

// Or, alternativly a bit shorter:
$temp = "_";
$a = "a";
$b = "b";
$hex = str_replace([$a, $b, $temp], [$temp, $a, $b] $hex);

另一种方法可能是str_split字符串, 并对每个字符使用array_map测试。 如果为a ,则返回b ,反之亦然。 否则返回原始值。

$hex = "abba test baab";
$hex = array_map(function ($x) {
    return ($x === 'a') ? 'b' : (($x === 'b') ? 'a' : $x);
}, str_split($hex));

echo implode('', $hex);

结果

baab test abba

演示版

我的解决方案适用于子字符串。 代码不清楚,但我想向您展示一种思维方式。

$html = "dasdfdasdff";
$firstLetter = "d";
$secondLetter = "a";
$firstLetterPositions = array();
$secondLetterPositions = array();

$lastPos = 0;
while (($lastPos = strpos($html, $firstLetter, $lastPos))!== false) {
    $firstLetterPositions[] = $lastPos;
    $lastPos = $lastPos + strlen($firstLetter);
}

$lastPos = 0;
while (($lastPos = strpos($html, $secondLetter, $lastPos))!== false) {
    $secondLetterPositions[] = $lastPos;
    $lastPos = $lastPos + strlen($secondLetter);
}

for ($i = 0; $i < count($firstLetterPositions); $i++) {
    $html = substr_replace($html, $secondLetter, $firstLetterPositions[$i], count($firstLetterPositions[$i]));
}

for ($i = 0; $i < count($secondLetterPositions); $i++) {
    $html = substr_replace($html, $firstLetter, $secondLetterPositions[$i], count($secondLetterPositions[$i]));
}
var_dump($html);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM