$srting = "test1 test1 test2 test2 test2 test1 test1 test2";
How can I change test1
values to test2
and test2
values to test1
?
When I use str_replace
and preg_replace
all values are changed to the last array value.
Example:
$pat = array();
$pat[0] = "/test1/";
$pat[1] = "/test2/";
$rep = array();
$rep[0] = "test2";
$rep[1] = "test1";
$replace = preg_replace($pat,$rep,$srting) ;
Result:
test1 test1 test1 test1 test1 test1 test1 test1
This should work for you:
<?php
$string = "test1 test1 test2 test2 test2 test1 test1 test2";
echo $string . "<br />";
echo $string = strtr($string, array("test1" => "test2", "test2" => "test1"));
?>
Output:
test1 test1 test2 test2 test2 test1 test1 test2
test2 test2 test1 test1 test1 test2 test2 test1
Checkout this DEMO: http://codepad.org/b0dB95X5
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