我有这个函数,它返回一个友好的url字符串。
public static function getUrlFriendlyString($str) {
// convert spaces to '-', remove characters that are not alphanumeric
// or a '-', combine multiple dashes (i.e., '---') into one dash '-'.
$_str = preg_replace("[-]", "-", preg_replace("[^a-z0-9-]", "",
strtolower(str_replace(" ", "-", $str))));
return substr($_str, 0, 40);
}
无论如何,如果我有这样的字符串:
"Product with vitamins, protein, and a lot of good stuff"
结果字符串是:
"product-with-vitamins,-protein,-and-a-lot-of-good-stuff"
正如您所看到的,它不会从字符串中删除逗号:/而我对正则表达式的了解是null
。
答案 0 :(得分:1)
您遗漏了正则表达式周围的分隔符,因此使用[
和]
作为分隔符。结果,他们没有被视为字符类操作符。
如果要将多个-
压缩为一个,则正则表达式为/-+/
,而不是[-]
。
public static function getUrlFriendlyString($str) {
// convert spaces to '-', remove characters that are not alphanumeric
// or a '-', combine multiple dashes (i.e., '---') into one dash '-'.
$_str = preg_replace("/-+/", "-", preg_replace("/[^a-z0-9-]/", "",
strtolower(str_replace(" ", "-", $str))));
return substr($_str, 0, 40);
}