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.
Another way could be to str_split the string and use array_map test per character. If
a
, returnb
and vice versa. Else return the original value.Result
Demo
My solution works for a substrings. The code is not clear but I want to show you a way of thinking.
Use a Temp value (which doesnt occur in your string. Could be anything):
Just use
strtr
. It's what it was designed for:Output:
The key functionality that helps here is that when
strtr
is called in the two argument form:This is what stops the
a
that was replaced byb
then being replaced bya
again.Demo on 3v4l.org
We could just try to substitute some third intermediate value for
B
, then replace allA
toB
, and then replace the marker back toA
. 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
orB
, and swapping accordingly.Note also that this approach is efficient, and only requires walking down the input string once.