简体   繁体   中英

problem with regular expressions php

/any_string/any_string/any_number

with this regular expression:

/(\w+).(\w+).(\d+)/

It works, but I need this url:

/specific_string/any_string/any_string/any_number

And I don't know how to get it. Thanks.

/(specific_string).(\\w+).(\\w+).(\\d+)/

Though note that the . s in your regular expression technically match any character and not just the /

/(specific_string)\\/(\\w+)\\/(\\w+)\\/(\\d+)/

This will have it match only slashes.

这将匹配第二个URL:

"/(\w+)\/(\w+)\/(\w+)\/(\d+)/"
/\/specific_string\/(\w+).(\w+).(\d+)/

只需在regexp中插入specific_string:

/specific_string\/(\w+)/(\w+)/\d+)/

更改了外部定界符的另一个变体,以避免不必要的转义:

preg_match("#/FIXED_STRING/(\w+)/(\w+)/(\d+)#", $_SERVER["REQUEST_URI"],

I would use something like this:

"/\/specific_string\/([^\/]+)\/([^\/]+)\/(\d+)/"

I use [^\\/]+ because that will match anything that is not a slash. \\w+ will work almost all the time, but this will also work if there is an unexpected character in the path somewhere. Also note that my regex requires the leading slash.

If you want to get a little more complicated, the following regex will match both of the patterns you provided:

"/^(?:\/specific_string)*\/([^\/]+)\/([^\/]+)\/(\d+)$/"

This will match:

"/any_string/any_string/any_number"
"/specific_string/any_string/any_string/any_number"

but it will not match

"/some_other_string/any_string/any_string/any_number"

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