生成友好 URL 字符串的函数未删除逗号

Function to generate Friendly URL Strings is not removing Commas

我有这个功能 returns 我是一个友好的 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.

您省略了正则表达式周围的分隔符,因此它使用 [] 作为分隔符。因此,它们未被视为字符 class 运算符。

如果要将多个 - 压缩为一个,正则表达式是 /-+/,而不是 [-]

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);
}