Suppose there's a string "foo boo foo boo" I want to replace all fooes with boo and booes with foo. Expected output is "boo foo boo foo". What I get is "foo foo foo foo". How to get expected output rather than current one?
$a = "foo boo foo boo";
echo "$a\n";
$b = str_replace(array("foo", "boo"), array("boo", "foo"), $a);
echo "$b\n";
//expected: "boo foo boo foo"
//outputs "foo foo foo foo"
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
Perhaps using a temporary value like coo.
sample code here,
$a = "foo boo foo boo";
echo "$a\n";
$b = str_replace("foo","coo",$a);
$b = str_replace("boo","foo",$b);
$b = str_replace("coo","boo",$b);
echo "$b\n";
First foo
to zoo
. Then boo
to foo
and last zoo
to boo
$search = array('foo', 'boo', 'zoo');
$replace = array('zoo', 'foo', 'boo');
echo str_replace($search, $replace, $string);
If as in this example that is the order of your case then using explode
and array_reverse
functions can be handy as well:
//the original string
$a = "foo boo foo boo";
//explodes+reverse+implode
$reversed_a = implode(' ', array_reverse(explode(' ', $a)));
//gives boo foo boo foo
PS: May not be memory friendly and may not satisfy all cases surrounding replacement though, but its simply satisfy the example you gave. :)
$a = "foo boo foo boo";
echo "$a\n";
$a = str_replace("foo", "x", $a);
$a = str_replace("boo", "foo", $a);
$a = str_replace("x", "boo", $a);
echo "$a\n";
note that "x" cannot occur in $a
Try it
$a = "foo boo foo boo";
echo "$a\n";
$b = str_replace(array("foo", "boo","[anything]"), array("[anything]", "foo","boo"), $a);
echo "$b\n";
来源:https://stackoverflow.com/questions/17850603/swap-two-words-in-a-string-php