PHP str_将空格替换为短划线,但短划线太多

PHP str_将空格替换为短划线,但短划线太多,php,string,str-replace,Php,String,Str Replace,我这里有一个字符串photo-of-day-2011,我需要看起来像photo-of-day-2011,当我进行stru替换时,我得到以下输出: 当日照片--2011我能做些什么来解决这个问题 代码如下: $albumName = 'photo of the day - 2011'; (this comes from a db and cannot change it) $albumName = str_replace(" ", "-", $albumName); 您可以使用更强大的,指示它用

我这里有一个字符串
photo-of-day-2011
,我需要看起来像
photo-of-day-2011
,当我进行stru替换时,我得到以下输出:

当日照片--2011
我能做些什么来解决这个问题

代码如下:

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

您可以使用更强大的,指示它用单个破折号替换破折号和/或空格:

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

[\s-]+
是一个匹配“一个或多个:空格和破折号”的选项。

您应该将Jon的答案标记为正确,以帮助他人。