How to replace multiple items from a text string in PHP?

James Brandon picture James Brandon · Feb 22, 2012 · Viewed 92.2k times · Source

I want to be able to replace spaces with - but also want to remove commas and question marks. How can I do this in one function?

So far, I have it replacing spaces:

str_replace(" ","-",$title)

Answer

napolux picture napolux · Feb 22, 2012

You can pass arrays as parameters to str_replace(). Check the manual.

// Provides: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = ["fruits", "vegetables", "fiber"];
$yummy   = ["pizza", "beer", "ice cream"];

$newPhrase = str_replace($healthy, $yummy, $phrase);