Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_replace() for multiple value replacement

Tags:

php

Is there any possibility to use str_replace for multiple value replacement in a single line. For example i want to replace ' ' with '-' and '&' with '' ?

like image 572
user3754380 Avatar asked Jul 03 '14 13:07

user3754380


2 Answers

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.

like image 96
Boaz Avatar answered Sep 20 '22 03:09

Boaz


str_replace([' ','-','&'],'',$text); 
like image 27
user14255532 Avatar answered Sep 24 '22 03:09

user14255532