Reputation: 810
I am trying to build a regex in PHP so that
/test/randomstring1/randomstring2
matches
/test/randomstring1/randomstring2/
matches
/test/randomstring1/randomstring2/randomstring3
does not match
I've come up with
/test\/(.+?)\/.*[^\/]/
It works fine for the 2 first cases but the third also matches. Could someone help me to figure out the thing that I am missing? Thanks!
Upvotes: 1
Views: 306
Reputation: 626709
Note that .
matches any char but line break chars. .*
will match as many chars other than line break chars as possible.
You may use
preg_match('~^/test/([^/]+)/([^/]+)/?$~', $text, $matches)
See the regex demo
Details
^
- start of string/test/
- a literal substring([^/]+)
- Group 1: any one or more chars other than /
/
- a /
char([^/]+)
- Group 2: any one or more chars other than /
/?
- an optional /
$
- end of string.Upvotes: 1