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

107,594

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);
Share:
107,594
James Brandon
Author by

James Brandon

Updated on July 08, 2022

Comments

  • James Brandon
    James Brandon almost 2 years

    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)