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.
I tried this code.
$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.
Just use strtr. It's what it was designed for:
$string = "abcbca";
echo strtr($string, array('a' => 'b', 'b' => 'a'));
Output:
bacacb
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.
This is what stops the a that was replaced by b then being replaced by a again.
Demo on 3v4l.org
We could just try to substitute some third intermediate value for B, then replace all A to B, and then replace the marker back to A. But this always leaves open the possibility that the marker character might already appears somewhere in the string.
A safer approach is to covert the input string into an array of characters, and then walk down the array simply checking each index for A or B, and swapping accordingly.
$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
Note also that this approach is efficient, and only requires walking down the input string once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With