【发布时间】:2014-06-03 08:08:37
【问题描述】:
我正在编写一个自定义博客脚本,其中的一部分是使用 slug 作为帖子 URL。到目前为止我的代码是
public function get_slug($str) {
// convert to lowercase
$str = strtolower($str);
// remove special chars
$str = preg_replace('/[^a-zA-Z0-9]/i', ' ', $str);
// remove what space from beginning and end
$str = trim($str);
// remove repeat spaces
$str = preg_replace('/\s+/', ' ', $str);
// replace spaces with hyphens
$str = preg_replace('/\s+/', '-', $str);
return $str;
}
这对大多数部分都很有效,但是我注意到如果单词中间有一个特殊的字符,它只是用连字符替换它,将“can't”变成“can-t”而不是“cant” '
虽然在预设时我可以编辑数据库并手动修复它,但我希望它自动从单词中间去除特殊字符而不用连字符替换它们。
【问题讨论】:
-
查看this function 作为这个的潜在替代品。
-
尝试在第一次替换时将空格更改为空字符串。