【问题标题】:Function to generate Friendly URL Strings is not removing Commas生成友好 URL 字符串的函数不会删除逗号
【发布时间】: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


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 2019-02-12
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多