Raphael Gbologah Raphael Gbologah - 3 months ago 7
PHP Question

Php Regular Expression Complex Matching

I'm working on a php mvc routing system and i need my router to be able to get the various parts of the url and map it accordingly like in this example:

url = controller/method/parameters/another/something/page/7


should map to:

controller = controller, method = method, parameters = parameters/another/something, page = 7


currently am only able to match

controller/method/parameter/page/7


with this regex:

{controller}/{method}/{parameters:[a-z0-9-]+}/page/{page:\d+}


which translates into this pattern:

/^(?P<controller>[a-z-]+)\/(?P<method>[a-z-]+)\/(?P<parameters>[a-z0-9-]+)\/page\/(?P<page>\d+)$/


I am using named captures to get the parts. i need help with the regex to use to get the result as stated above.

Answer

You need to allow /s in your parameter's character class.

/^(?P<controller>[a-z-]+)\/(?P<method>[a-z-]+)\/(?P<parameters>[a-z0-9\/-]+)\/page\/(?P<page>\d+)$/

Demo: https://regex101.com/r/nX7cZ8/1

Comments