swap two words in a string php

前端 未结 6 1120
灰色年华
灰色年华 2020-12-03 14:30

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 fo

相关标签:
6条回答
  • 2020-12-03 14:55

    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";
    
    0 讨论(0)
  • 2020-12-03 14:56

    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

    0 讨论(0)
  • 2020-12-03 15:03

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

    0 讨论(0)
  • 2020-12-03 15:05

    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";
    
    0 讨论(0)
  • 2020-12-03 15:07

    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);
    
    0 讨论(0)
  • 2020-12-03 15:19
    $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

    0 讨论(0)
提交回复
热议问题