PHP用连字符替换所有空格 [英] PHP replace all spaces with hyphens

查看:219
本文介绍了PHP用连字符替换所有空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在脚本中用连字符替换所有空格,如下所示:

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

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

我要替换的是Band Name - Song Name因此,在这种情况下,如果我有类似的内容:

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

Metallica - Hero of the Day

我最终得到:

 Metallica---Hero-of-the-Day

注意到那3个---吗?

您能建议一种优雅的方法,以仅一个-而不是3结尾.

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

在完成str_replace之前,我可以继续做,但是那看不对.

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

推荐答案

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

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

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

这篇关于PHP用连字符替换所有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆