正则表达式。如果/ category /以数字开头的部分URL返回true。怎么样?

时间:2018-04-19 12:24:45

标签: php regex

有一些网址类型:

  1. https://mysite.com/page-title
  2. https://mysite.com/category/page-title
  3. https://mysite.com/category/123-page-title(123-它的页面ID)
  4. 我需要检查URL,是否以数字开头(类型3)。 I.e url =是类型3,然后返回TRUE。

    这需要什么样的正则表达式?

3 个答案:

答案 0 :(得分:1)

据我所知,ID可以在域名地址之后的任何地方,因此:

false https: //mysite.com/123-page-title
false https: //mysite.com/page-title
false https: //mysite.com/category/page-title
true  https: //mysite.com/category/123-page-title
false  https: //mysite.com/1-page-title

因此,您需要的正则表达式为:'/mysite\.com.*/category/\d+?.*/'

mysite\.com.*/\d+?.*
   mysite matches the characters mysite literally (case sensitive)
   \. matches the character . literally (case sensitive)
   com matches the characters com literally (case sensitive)
 .* matches any character (except for line terminators)
    * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    /category/ matches the characters /category/ literally (case sensitive)
    \d+? matches a digit (equal to [0-9])
      +? Quantifier — Matches between one and unlimited times, as few times as possible, expanding as needed (lazy)
 .* matches any character (except for line terminators)
   * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)

在此处查看:https://regex101.com/r/qv8tim/2

答案 1 :(得分:0)

我对正则表达式满足此要求的建议如下:

.*?category\/[0-9]+.*

这将匹配短语category/之前的任何内容,然后要求至少跟随一个数字,然后匹配该行的其余部分。

答案 2 :(得分:0)

每个人都喜欢正则表达式: - )

不使用regex的解决方案:

function is_valid($url)
{
    $pieces = explode('/', parse_url($url, PHP_URL_PATH));
    return isset($pieces[2]) && (int)$pieces[2];
}

查看实际操作:https://3v4l.org/BqcTs