2

我在这里有这个字符串,当我执行 str_replace 时,photo of the day - 2011我需要看起来像这样,我得到这个输出: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);
4

1 回答 1

11

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

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

[\s-]+是匹配“一个或多个:空格和破折号”的正则表达式。

于 2013-08-19T18:47:45.890 回答