views:

1059

answers:

4

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'.

+1  A: 

str_replace() does that.

chaos
+6  A: 

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
);
lpfavreau
A: 

For what you've got there, just pass that array into str_replace as both the search and replace (using array_keys on the search parameter if you want to keep the array as-is).

Ant P.
A: 

Thanks! This is really nice. :)

Junaid Atari