Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there an inbuilt PHP function to replace multiple values inside a string with an array that dictates exactly what is replaced with what?

For example:

$searchreplace_array = Array('blah' => 'bleh', 'blarh' => 'blerh');
$string = 'blah blarh bleh bleh blarh';

And the resulting would be: 'bleh blerh bleh bleh blerh'.

like image 213
atomicharri Avatar asked Feb 11 '09 01:02

atomicharri


People also ask

How to replace multiple values in PHP?

Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.

How do you replace multiple occurrences of a string in Java?

You can replace all occurrence of a single character, or a substring of a given String in Java using the replaceAll() method of java. lang. String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String.

How to replace all character in a string in PHP?

The str_replace() is a built-in function in PHP and is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.

How do I replace a word in a string in PHP?

The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.


2 Answers

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
); 
like image 63
lpfavreau Avatar answered Oct 30 '22 12:10

lpfavreau


$string = 'blah blarh bleh bleh blarh';
$trans = array("blah" => "blerh", "bleh" => "blerh");
$result = strtr($string,$trans);

You can check the manual for detailed explanation.

like image 24
nithi Avatar answered Oct 30 '22 13:10

nithi