1

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
  • 1
    You need '~^/test/([^/]+)/([^/]+)/?$~' Commented Dec 14, 2019 at 22:15

1 Answer 1

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.