Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中替换多个值_Php_Preg Replace_Str Replace - Fatal编程技术网

如何在php中替换多个值

如何在php中替换多个值,php,preg-replace,str-replace,Php,Preg Replace,Str Replace,如何将test1值更改为test2,将test2值更改为test1? 当我使用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) ; $t

如何将
test1
值更改为
test2
,将
test2
值更改为
test1

当我使用
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) ;
$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);

这应该适合您:

test1 test1 test1 test1 test1 test1 test1 test1 

检查此演示:

使用preg\u replace,您可以用临时值替换测试值,然后用交换的测试值替换临时值

test1 test1 test2 test2 test2 test1 test1 test2
test2 test2 test1 test1 test1 test2 test2 test1
最简单的方法是使用函数进行不区分大小写的替换:

test1 test1 test2 test2 test2 test1 test1 test2
test2 test2 test1 test1 test1 test2 test2 test1
结果:

$pat = array();
$pat[0] = "/test1/";
$pat[1] = "/test2/";
$rep = array();
$rep[0] = "test2";
$rep[1] = "test1";
$replace = preg_replace($pat,$rep,$srting) ;
$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);

您可以尝试使用中介,例如在交换变量中的值时,@Rizier123您的示例适用于区分大小写的替换,对于区分大小写的替换,可以使用此处不需要的
stru ireplace
@ValeryViktorovsky,但在手册注释中已经有一个:
$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);
test2 test2 test1 test1 test1 test2 test2 test1