简体   繁体   中英

PHP replace all spaces with hyphens

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.

使用正则表达式使用一个连字符更改多个空格或连字符:

$final = preg_replace('#[ -]+#', '-', $text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM