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"
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.
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With