str_replace() for multiple value replacement

str_replace() accepts arrays as arguments.

For example:

$subject="milk is white and contains sugar";
str_replace(array('sugar', 'milk'), array('sweet', 'white'), $subject);

In fact, the third argument can also be an array, so you can make multiple replacements in multiple values with a single str_replace() call.

For example:

$subject = array('milk contains sugar', 'sugar is white', 'sweet as sugar');
str_replace(array('sugar', 'milk'), array('sweet', 'white'), $subject);

As others have noted, this is clearly stated in the manual:

search
The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

replace
The replacement value that replaces found search values. An array may be used to designate multiple replacements.

subject
The string or array being searched and replaced on, otherwise known as the haystack.

Leave a Comment