简体   繁体   English

PHP 正则表达式 preg_match 以识别 url 模式

[英]PHP regex preg_match to identify url pattern

Is there any way to make rule allow only example 1 and 3 and not all 4 of them?有没有办法让规则只允许示例 1 和 3 而不是全部 4?

/^(en\/|)([\d]{1,3})([-])(.+?)([\/])$/

examples:例子:

  1. 12-blog/ 12-博客/
  2. 12-blog/blog2/ 12-博客/blog2/
  3. en/12-blog/ zh/12-博客/
  4. en/12-blog/blog2/ zh/12-博客/blog2/

https://www.phpliveregex.com/p/tFe https://www.phpliveregex.com/p/tFe

You might use an optional part for en/ followed by match 1-3 digits, - and match not a / 1+ times using a negated character class.您可以使用en/的可选部分,后跟匹配 1-3 位数字, -并且使用否定字符 class 不匹配/ 1+ 次。

Note that you can omit the square brackets for [\d] , [-] and [\/] .请注意,您可以省略[\d][-][\/]的方括号。 If you choose a different delimiter than / you don't have to escape the forward slash.如果您选择与/不同的分隔符,则不必转义正斜杠。

^(?:en/)?\d{1,3}-[^/]+/$

In parts在零件

  • ^ Start of string ^字符串开头
  • (?:en/)? Optionally match en/可选匹配en/
  • \d{1,3} Match 1-3 digits \d{1,3}匹配 1-3 位数字
  • - Match literally -从字面上匹配
  • [^/]+/ Match 1+ times any char except / [^/]+/匹配除/之外的任何字符 1+ 次
  • $ End of string $字符串结尾

Regex demo |正则表达式演示| Php demo Php 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM