Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swap two words in a string php

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"
like image 964
codefreak Avatar asked Jul 25 '13 06:07

codefreak


People also ask

How can I replace words in a string in PHP?

The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.

How do I swap characters in a string?

As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created). To do modifications on string stored in a String object, we copy it to a character array, StringBuffer, etc and do modifications on the copy object.


3 Answers

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

like image 89
Orangepill Avatar answered Oct 07 '22 22:10

Orangepill


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";
like image 32
Fallen Avatar answered Oct 07 '22 22:10

Fallen


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);
like image 32
Bora Avatar answered Oct 08 '22 00:10

Bora