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

时间:2013-08-19 18:46:22

标签: php string str-replace

我在这里使用此字符串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);

1 个答案:

答案 0 :(得分:11)

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

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

[\s-]+regular expression,匹配“以下一个或多个:空格和短划线”。