Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace str1 with str2 and vice versa

Tags:

php

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?

like image 870
Vahid2015 Avatar asked Feb 13 '19 18:02

Vahid2015


People also ask

How do you replace each letter in a string in python?

Python String replace()The replace() method replaces each matching occurrence of the old character/text in the string with the new character/text.


1 Answers

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.

like image 127
AbraCadaver Avatar answered Oct 01 '22 15:10

AbraCadaver