简体   繁体   English

PHP 正则表达式 url 匹配

[英]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) tag/从字面上匹配(也许/tag/\btag会更具体)
  • [^/\s]+ Match 1+ occurrences of any char except / or a whitespace char [^/\s]+匹配除/或空白字符之外的任何字符的 1+ 次出现
  • (?: Non capture group (?:非捕获组
    • /(?:\?.*)? Match / followed by an optional part to match ?匹配/后跟一个可选部分来匹配? and the rest of the string和字符串的 rest
  • )? Close group and make it optional关闭组并使其可选
  • $ End of string $字符串结尾

Regex demo正则表达式演示

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

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