【问题标题】:How to replace multiple values in php如何在php中替换多个值
【发布时间】:2015-03-02 07:07:51
【问题描述】:
$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 

【问题讨论】:

标签: php preg-replace str-replace


【解决方案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

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

【讨论】:

  • @Rizier123 您的示例适用于区分大小写的替换,对于不区分大小写的替换,可以使用str_ireplace
  • @ValeryViktorovsky 这不是必需的,但在手动 cmets 中已经有一个:php.net/manual/en/function.strtr.php#82051
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 2020-04-14
      • 2018-04-05
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      相关资源
      最近更新 更多