PHP str_replace用破折号替换空格,但破折号太多


PHP str_replace replace space with dash, but too many dash

我这里有这个字符串photo of the day - 2011,当我执行str_replace时,我需要看起来像photo-of-the-day-2011,我得到的输出是:

photo-of-the-day---2011我能做些什么来解决这个问题?

这是代码:

$albumName = 'photo of the day - 2011'; (this comes from a db and cannot change it)
$albumName = str_replace(" ", "-", $albumName);

您可以使用更强大的preg_replace,指示它用一个短划线替换短划线和/或空格:

$name = preg_replace('/['s-]+/', '-', $name);

['s-]+是一个正则表达式,它匹配"一个或多个:空白和短划线"。