Noah
Noah

Reputation: 810

PHP Regex to match a URL pattern

I am trying to build a regex in PHP so that

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

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

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

Related Questions