简体   繁体   中英

PHP regex url matching

I have some example:

mysite.com/tag/HD+Wallpaper           //match
mysite.com/tag/HD+Wallpaper/          //match
mysite.com/tag/HD+Wallpaper?page=     //match
mysite.com/tag/HD+Wallpaper/?page=    //match
  
mysite.com/tag/HD+Wallpaper/sdadasdas    //not match

with "HD+Wallpaper" is a param

i try:

^tag/(.+?)(|\/|\?(.*?))$i

How can i fix it? TY

You could try following regex

tag\/.*?(?=\/|\?|$)

Demo

Note: In the demo, I added backslash \ to escape /

This regex should work for you:

tag\/([^\/]*?)(?=\/$|\/\?|\?|$)

Demo

You might use

tag/[^/\s]+(?:/(?:\?.*)?)?$

Explanation

  • tag/ Match literally (perhaps /tag/ or \btag would be more specific)
  • [^/\s]+ Match 1+ occurrences of any char except / or a whitespace char
  • (?: Non capture group
    • /(?:\?.*)? Match / followed by an optional part to match ? and the rest of the string
  • )? Close group and make it optional
  • $ End of string

Regex 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