Reputation: 3360
I want to replace word1
with word2
and word2
with word1
for this string :
word1 word2
here is what i want to do :
1.replace word1 with word2 => I get : word2 word2
2.replace word2 with word1 => I should get word2 word1 .
but I get this :
word1 word1
becuase str_replace function also replace the first replaced word1.
How to avoid this kind of problems ?
thanks
Upvotes: 1
Views: 299
Reputation: 2507
You can't achieve this by str_replace. Use string translation (strtr) which was designed to do so instead:
$words = 'word1 word2';
$wordsReplaced = strtr($words, [
'word1' => 'word2',
'word2' => 'word1'
]);
Upvotes: 1