Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) 
like image 860
James Brandon Avatar asked Feb 22 '12 11:02

James Brandon


People also ask

How can I replace multiple words in a string in PHP?

Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.

How can I replace part of a string in PHP?

The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.

How can I replace one word with another in PHP?

Answer: Use the PHP str_replace() function You can use the PHP str_replace() function to replace all the occurrences of a word within a string.


1 Answers

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); 
like image 66
napolux Avatar answered Sep 16 '22 15:09

napolux