swap two words in a string php

前端 未结 6 1226
灰色年华
灰色年华 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 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. :)

提交回复
热议问题