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!
asked Dec 14, 2019 at 22:13
1 Answer 1
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.
answered Dec 14, 2019 at 22:30
Sign up to request clarification or add additional context in comments.
Comments
lang-php
'~^/test/([^/]+)/([^/]+)/?$~'