How to replace multiple values in php

点点圈 提交于 2019-11-26 11:36:22

问题


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

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) ;

Result:

test1 test1 test1 test1 test1 test1 test1 test1 

回答1:


This should work for you:

<?php

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

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

?>

Output:

test1 test1 test2 test2 test2 test1 test1 test2
test2 test2 test1 test1 test1 test2 test2 test1

Checkout this DEMO: http://codepad.org/b0dB95X5




回答2:


The simplest way is use str_ireplace function for case insensitive replacement:

$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);

Result:

test2 test2 test1 test1 test1 test2 test2 test1



回答3:


With preg_replace you can replace test value with the temporary values then replace the temporary value with interchanged test values

$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;

output:

test1 test1 test2 test2 test2 test1 test1 test2
test2 test2 test1 test1 test1 test2 test2 test1


来源:https://stackoverflow.com/questions/27767777/how-to-replace-multiple-values-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!