Unkn0wn
Unkn0wn

Reputation: 88

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 

Upvotes: 4

Views: 726

Answers (3)

Valery Viktorovsky
Valery Viktorovsky

Reputation: 6726

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

Upvotes: 1

SteveTz
SteveTz

Reputation: 232

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

Upvotes: 0

Rizier123
Rizier123

Reputation: 59681

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

Upvotes: 16

Related Questions