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

PhpStringStr Replace

Php Problem Overview


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)

Php Solutions


Solution 1 - Php

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames BrandonView Question on Stackoverflow
Solution 1 - PhpnapoluxView Answer on Stackoverflow