如何在php中替换多个值

时间:2015-01-04 16:38:14

标签: php preg-replace str-replace

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

如何将test1值更改为test2test2值为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 

3 个答案:

答案 0 :(得分:16)

这应该适合你:

<?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

答案 1 :(得分:1)

最简单的方法是使用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

答案 2 :(得分:0)

使用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