php 43 lines · 8 steps

Compiling route patterns into regex in PHP

A Route class turns URL patterns like /users/{id} into a regex and matches incoming requests, extracting named parameters.

Explained by highlit
1final class Route
2{
3 private string $regex;
4 private array $paramNames = [];
5 
6 public function __construct(
7 public readonly string $method,
8 public readonly string $pattern,
9 public readonly mixed $handler,
10 ) {
11 $this->compile();
12 }
13 
14 private function compile(): void
15 {
16 $regex = preg_replace_callback(
17 '#\{(\w+)(?::([^}]+))?\}#',
18 function (array $m): string {
19 $this->paramNames[] = $m[1];
20 $constraint = $m[2] ?? '[^/]+';
21 return '(' . $constraint . ')';
22 },
23 $this->pattern,
24 );
25 
26 $this->regex = '#^' . $regex . '$#';
27 }
28 
29 public function match(string $method, string $path): ?array
30 {
31 if (strcasecmp($method, $this->method) !== 0) {
32 return null;
33 }
34 
35 if (!preg_match($this->regex, $path, $matches)) {
36 return null;
37 }
38 
39 array_shift($matches);
40 
41 return array_combine($this->paramNames, array_map('rawurldecode', $matches));
42 }
43}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Compiling a pattern once at construction time keeps per-request matching cheap.
  2. 2Capture groups and a parallel list of names let you pair matched values back to parameter keys.
  3. 3Optional inline constraints give patterns per-segment validation while defaulting to a safe catch-all.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Compiling route patterns into regex in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code