如何替换 php 中的多个值

How to replace multiple values in php

$srting = "test1 test1 test2 test2 test2 test1 test1 test2";

如何将 test1 值更改为 test2 并将 test2 值更改为 test1
当我使用 str_replacepreg_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

查看此演示:http://codepad.org/b0dB95X5

使用 preg_replace 您可以用临时值替换测试值,然后用互换的测试值替换临时值

$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;

输出:

test1 test1 test2 test2 test2 test1 test1 test2
test2 test2 test1 test1 test1 test2 test2 test1

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

$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