简体   繁体   中英

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?

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

examples:

  1. 12-blog/
  2. 12-blog/blog2/
  3. en/12-blog/
  4. en/12-blog/blog2/

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.

Note that you can omit the square brackets for [\d] , [-] and [\/] . 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/
  • \d{1,3} Match 1-3 digits
  • - Match literally
  • [^/]+/ Match 1+ times any char except /
  • $ End of string

Regex demo | Php demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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