I have a regex like this basename/(.+)/(.+)/(.+)/?$
but the problem is this is a greedy regex.
I want to exclude certain strings on the 2nd match such that if it matches one of the blacklisted strings, it will return false..
This problem is connected to my other question on https://wordpress.stackexchange.com/questions/102246/wordpress-returns-404-on-custom-rewrite-rules
the only diffence is the approach.
Hope you guys can help me. Thanks!
EDIT: here is what im trying to work from: basename/(.+)/!(string1|string2|string3).*/(.+)/?$
(added from comments)
P.S. I’ve seen this but this doesn’t seem like what I wanted.
My first if/else regex condition, cool right 🙂 ?
basename/(.+)/(?(?=(?:bar|string2|string3)/)^|(.+))/(.+)/?$
So what does this mean ?
basename/
: matchbasename/
(.+)/
: anything until/
found and match/
(?(?=(?:bar|string2|string3)/)^|(.+))
: the tricky part, we’ll split this up:(?
: This means if(?=(?:bar|string2|string3)/)
: positive lookahead, check if there isbar/
orstring2/
, orstring3/
.^
: If the lookahead succeeded, then match this.^
means begin of line, since we are in the middle of a string, this will always return false !|(.+)
: Else, match everything until …bar/
orstring2/
orstring3/
, if there is a match then we’ll look for begin of line^
which will always return false (our intention) else match further(.*)
/(.+)/?$
: match/
, then anything until/
optionally.$
means end of line.Online demo
You’ll want to make catch group that has the same pattern (/dir) lazy matches (using ?).
For strings such as:
The following Regex would return false for the second two but catch the first:
PHP fiddle: http://phpfiddle.org/lite/code/1qr-iip
you could use
.*?
instead of.*
to make it ungreedy, but you’d probably be better with a greedy match that excludes/
. ie[^/]*
.Your question is not all that clear. I’m not sure what you’re doing with the
!(x|y|z)
construct. That!
is a literal. Is that what you intended?