How to replace multiple values ​​in php

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

How to change values test1to test2and test2to test1?
When I use str_replaceand preg_replace, all values ​​change to the last value of the array. 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 
+4
source share
3 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"));

?>

Conclusion:

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

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

+16
source

The easiest way is to use str_ireplace for a caseless 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
+1
source

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
0

Source: https://habr.com/ru/post/1569897/


All Articles