Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace multiple values in php

$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 
like image 723
Unkn0wn Avatar asked Dec 03 '22 18:12

Unkn0wn


1 Answers

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

like image 147
Rizier123 Avatar answered Dec 06 '22 10:12

Rizier123