$srting = "test1 test1 test2 test2 test2 test1 test1 test2";
如何将test1值更改为test2和将test2值更改为test1? 当我使用str_replace和preg_replace所有值都更改为最后一个数组值。例:
test1
test2
str_replace
preg_replace
$pat = array(); $pat[0] = "/test1/"; $pat[1] = "/test2/"; $rep = array(); $rep[0] = "test2"; $rep[1] = "test1"; $replace = preg_replace($pat,$rep,$srting) ;
结果:
test1 test1 test1 test1 test1 test1 test1 test1
这应该为您工作:
<?php $string = "test1 test1 test2 test2 test2 test1 test1 test2"; echo $string . "<br />"; echo $string = strtr($string, array("test1" => "test2", "test2" => "test1")); ?>
输出:
test1 test1 test2 test2 test2 test1 test1 test2 test2 test2 test1 test1 test1 test2 test2 test1
检出此DEMO:http : //codepad.org/b0dB95X5