PCRE Based Params
Dynamic routing with PCRE Based Params


PCRE based patterns

This guide assumes you have read Simple Routing

Basically, PCRE based patterns are just another way to use routes dynamically. This type of Route Patterns contain dynamic parts which can vary per request. The varying parts are named subpatterns and are defined using regular expressions.


  • /movies/(\d+)
  • /profile/(\w+)

Commonly used PCRE-based subpatterns within Dynamic Route Patterns are:

  • \d+ = One or more digits (0-9)
  • \w+ = One or more word characters (a-z 0-9 _)
  • [a-z0-9_-]+ = One or more word characters (a-z 0-9 _) and the dash (-)
  • .* = Any character (including /), zero or more
  • [^/]+ = Any character but /, one or more

Note: The PHP PCRE Cheat Sheet might come in handy.

The subpatterns defined in Dynamic PCRE-based Route Patterns are converted to parameters which are passed into the route handling function. Prerequisite is that these subpatterns need to be defined as parenthesized subpatterns, which means that they should be wrapped between parens:

// Bad $leaf->get('/hello/\w+', function($name) { echo 'Hello ' . htmlentities($name); }); // Good $leaf->get('/hello/(\w+)', function($name) { echo 'Hello ' . htmlentities($name); });
Note: The leading / at the very beginning of a route pattern is not mandatory, but is recommended.

When multiple subpatterns are defined, the resulting route handling parameters are passed into the route handling function in the order they are defined in:

$leaf->get('/movies/(\d+)/photos/(\d+)', function($movieId, $photoId) { echo 'Movie #' . $movieId . ', photo #' . $photoId); });

Next Steps

Optional sub-patterns
Simple Authentication