58

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)
Vlad
  • 17,655
  • 4
  • 40
  • 70
James Brandon
  • 1,260
  • 2
  • 16
  • 42
  • 2
    [You can pass multiple search values to `str_replace()`](http://php.net/manual/en/function.str-replace.php). – JJJ Feb 22 '12 at 11:29

1 Answers1

240

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);
napolux
  • 14,547
  • 9
  • 50
  • 69
  • 2
    I got confused expecting junk food to become healthier. Bad replacement ! LOL. Jokes apart, it'd been easier to have the function accepting a single array as "replace" argument in the form [search=>replace] – E Ciotti Dec 02 '17 at 13:06
  • 4
    To pass in a single associative array of replacements, you'd then use array_keys($replacements) and array_values($replacements) as the respective parameters in the str_replace. See the first answer at https://stackoverflow.com/questions/535143/search-and-replace-multiple-values-with-multiple-different-values-in-php5 – matthewv789 Nov 04 '19 at 03:59
  • 1
    `str_replace` replaces each item in sequence, but you can also use [`strtr`](https://www.php.net/manual/en/function.strtr.php) to replace the items simultaneously. – Anderson Green Aug 16 '21 at 14:59
  • @AndersonGreen Best answer. Didn't get a star but saved me ! – Thanasis Sep 10 '21 at 17:04