$srting = \"test1 test1 test2 test2 test2 test1 test1 test2\";
How can I change test1
values to test2
and test2
The simplest way is use str_ireplace function for case insensitive replacement:
$text = "test1 tESt1 test2 tesT2 tEst2 tesT1 test1 test2";
$from = array('test1', 'test2', '__TMP__');
$to = array('__TMP__', 'test1', 'test2');
$text = str_ireplace($from, $to, $text);
Result:
test2 test2 test1 test1 test1 test2 test2 test1
With preg_replace you can replace test value with the temporary values then replace the temporary value with interchanged test values
$srting = "test1 test1 test2 test2 test2 test1 test1 test2";
$pat = array();
$pat[0] = '/test1/';
$pat[1] = '/test2/';
$rep = array();
$rep[1] = 'two'; //temporary values
$rep[0] = 'one';
$pat2 = array();
$pat2[0] = '/two/';
$pat2[1] = '/one/';
$rep2 = array();
$rep2[1] = 'test2';
$rep2[0] = 'test1';
$replace = preg_replace($pat,$rep,$srting) ;
$replace = preg_replace($pat2,$rep2,$replace) ;
echo $srting . "<br/>";
echo $replace;
output:
test1 test1 test2 test2 test2 test1 test1 test2
test2 test2 test1 test1 test1 test2 test2 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