swap two words in a string php

Use strtr

From the manual:

If given two arguments, the second should be an array in the form array(‘from’ => ‘to’, …). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

In this case, the keys and the values may have any length, provided that there is no empty key; additionaly, the length of the return value may differ from that of str. However, this function will be the most efficient when all the keys have the same size.

$a = "foo boo foo boo";
echo "$a\n";
$b = strtr($a, array("foo"=>"boo", "boo"=>"foo"));
echo "$b\n"; 

Outputs

foo boo foo boo
boo foo boo foo

In Action

Leave a Comment