【发布时间】:2015-04-10 00:53:17
【问题描述】:
我有这个函数可以返回一个友好的 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。
【问题讨论】:
-
为什么要用
-替换[-]?这没有任何作用。 -
不知
-
此外,如果您将空格转换为破折号,然后删除非字母数字字符,您的破折号就消失了!所以这是没有意义的
-
这里不是明确你想要达到的目标。
-
你可以使用 urlencode()
标签: php regex url preg-replace