如何在php中替换多个值 [英] How to replace multiple values in php

查看:95
本文介绍了如何在php中替换多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何将test1值更改为test2并将test2值更改为test1?
当我使用str_replacepreg_replace时,所有值都将更改为最后一个数组值. 示例:

How can I change test1 values to test2 and test2 values to test1 ?
When I use str_replace and preg_replace all values are changed to the last array value. Example:

$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

这篇关于如何在php中替换多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆