66

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
  • 18,195
  • 4
  • 41
  • 71
James Brandon
  • 1,350
  • 3
  • 16
  • 43
  • 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
  • I understand this has been answered, but for those that don't need array like @napolux answered below, this will work for you as well. `$text = "It's TIME on DAY in COUNTRY";` `$time = str_replace("TIME","05:00PM", $text);` `$day = str_replace("DAY","Monday", $time);` `$merge = str_replace("COUNTRY","US", $day);` `echo $merge;` – Dexter Dec 30 '22 at 14:37

1 Answers1

260

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
  • 15,574
  • 9
  • 51
  • 70
  • 3
    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
  • 5
    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
  • 2
    `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