如何在php中替换多个值

Unk*_*0wn 4 php preg-replace str-replace

$srting = "test1 test1 test2 test2 test2 test1 test1 test2";
Run Code Online (Sandbox Code Playgroud)

如何更改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) ;
Run Code Online (Sandbox Code Playgroud)

结果:

test1 test1 test1 test1 test1 test1 test1 test1 
Run Code Online (Sandbox Code Playgroud)

Riz*_*123 16

这应该适合你:

<?php

    $string = "test1 test1 test2 test2 test2 test1 test1 test2";

    echo $string . "<br />";
    echo $string = strtr($string, array("test1" => "test2", "test2" => "test1"));

?>
Run Code Online (Sandbox Code Playgroud)

输出:

test1 test1 test2 test2 test2 test1 test1 test2
test2 test2 test1 test1 test1 test2 test2 test1
Run Code Online (Sandbox Code Playgroud)

看看这个DEMO:http://codepad.org/b0dB95X5

  • `strtr()`的相关手册页:http://php.net/manual/en/function.strtr.php (3认同)