Str_Replace() for Multiple Value Replacement

Search and replace multiple values with multiple/different values in PHP5?

You are looking for str_replace().

$string = 'blah blarh bleh bleh blarh';
$result = str_replace(
array('blah', 'blarh'),
array('bleh', 'blerh'),
$string
);

// Additional tip:

And if you are stuck with an associative array like in your example, you can split it up like that:

$searchReplaceArray = array(
'blah' => 'bleh',
'blarh' => 'blerh'
);
$result = str_replace(
array_keys($searchReplaceArray),
array_values($searchReplaceArray),
$string
);

PHP replace multiple value using str_replace?

From the manual page for str_replace():

Caution

Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

For example, "m" is replaced with "Month", then the "h" in "Month" is replaced with "Hours", which comes later in the array of replacements.

strtr() doesn't have this issue because it tries all keys of the same length at the same time:

$date = strtr($key, array(
'y' => 'Year',
'm' => 'Month',
'd' => 'Days',
'h' => 'Hours',
'i' => 'Munites', // [sic]
's' => 'Seconds',
));

Str_replace for multiple items

str_replace() can take an array, so you could do:

$new_str = str_replace(str_split('\\/:*?"<>|'), ' ', $string);

Alternatively you could use preg_replace():

$new_str = preg_replace('~[\\\\/:*?"<>|]~', ' ', $string);

how to Str_replace for multiple items

You can use strtr() and an associative array to do this:

<?php
$text = "Text about -- and -+- !";
$replacements = [
"--" => "/",
"-+-" => ":",
];
echo strtr($text, $replacements); // Text about / and : !

To add more replacements, simply keep adding more elements to the $replacements array. Index is the string to look for, value is the replacement.

  • Demo
  • strtr() reference

replace multiple values in a string

A simple option would be chartr

chartr('1234', '0000', string)
#[1] "0 0 0 0 5 6 7 8 9"

How to replace multiple values in php

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



Related Topics



Leave a reply



Submit