swap two words in a string php

岁酱吖の 提交于 2019-11-28 09:58:39

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

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";
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!