I already have a routing method that matches this pattern:
/hello/:name
that set name to be a dynamic path, I want to know how to make it:
/hello/{name}
with the same regex. How to add optional trailing slash to it, like this?
/hello/:name(/)
or
/hello/{name}(/)
This is the regex I use for /hello/:name
@^/hello/([a-zA-Z0-9\-\_]+)$@D
The regex is auto generated from PHP class
private function getRegex($pattern){
$patternAsRegex = "@^" . preg_replace('/\\\:[a-zA-Z0-9\_\-]+/', '([a-zA-Z0-9\-\_]+)', preg_quote($pattern)) . "$@D";
return $patternAsRegex;
}
If the route is /hello/:name(/)
I want it to make the match with optional thing else continue normal
Simply replace your regex with this for optional
/
:This will create a regular expression for the
$pattern
route with both:name
and{name}
parameters, as well as the optional slash. As a bonus, it will also add a?<name>
to make the parameter easier to handle down the line.For example, a route pattern of
/hello/:name(/)
will get the regular expression@^/hello/(?<name>[a-zA-Z0-9\_\-]+)/?$@D
. When matched with a URL, likepreg_match( <regex above>, '/hello/sarah', $matches)
that would give you$matches['name'] == 'sarah'
.There are some tests to be found below the actual function.
Output: