Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP replace all spaces with hyphens

Tags:

php

I replace all spaces with hyphens in my script like this:

$final = str_replace(' ','-',$final); The - is the only thing I replace.

What I'm replacing are Band Name - Song Name So in this case, if I had something like:

Metallica - Hero of the Day

I end up with:

 Metallica---Hero-of-the-Day

Notice the 3 --- there?

Can you suggest an elegant way of ending up with just one - instead of 3.

I can keep doing str_replace until it's done, but that doesn't see right.

like image 504
jmenezes Avatar asked Nov 10 '13 14:11

jmenezes


People also ask

How do you replace spaces with dashes?

Use the replace() method to replace spaces with dashes in a string, e.g. str. replace(/\s+/g, '-') . The replace method will return a new string, where each space is replaced by a dash.

How can I replace multiple characters 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.


1 Answers

Use a regular expression changing multiple spaces or hyphens with one hyphen:

$final = preg_replace('#[ -]+#', '-', $text);
like image 168
Peter van der Wal Avatar answered Oct 27 '22 14:10

Peter van der Wal