swap two words in a string php

回眸只為那壹抹淺笑 提交于 2019-11-27 03:19:19

问题


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"

回答1:


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




回答2:


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";



回答3:


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);



回答4:


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. :)




回答5:


$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




回答6:


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

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