Suppose I have a text like the following
John is John and Sara is Sara
I want to turn it to:
Sara is Sara and John is John
If I execute str_replace("John", "Sara", $input)
, then there will be no more John and str_replace("Sara", "John", $input)
would turn all names to John. So how can I do this?
Is there a built-in function to achieve this?
Python String replace()The replace() method replaces each matching occurrence of the old character/text in the string with the new character/text.
You can use an array in order to not run multiple replacements, however str_replace
will not yield the correct results. Given John is John and Sara is Sara
:
$result = str_replace(['John', 'Sara'], ['Sara', 'John'], $string);
Yields: John is John and John is John
You need to use strtr
because of the way it searches, and replaces eliminate this issue:
$result = strtr($string, ['John'=>'Sara', 'Sara'=>'John']);
Yields: Sara is Sara and John is John
From the manual strstr:
The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.
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