一尘不染

如何在php中替换多个值

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

阅读 315

收藏
2020-05-29

共1个答案

一尘不染

这应该为您工作:

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

2020-05-29