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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Compiling a pattern once at construction time keeps per-request matching cheap.
- 2Capture groups and a parallel list of names let you pair matched values back to parameter keys.
- 3Optional inline constraints give patterns per-segment validation while defaulting to a safe catch-all.
Related explainers
php
public function customerTotals(Request $request): Collection { return DB::table('orders') ->join('customers', 'customers.id', '=', 'orders.customer_id')
Building an aggregate report with Laravel's query builder
query builder
aggregation
conditional queries
Intermediate
8 steps
java
public final class DeepCopier { private static final ObjectMapper MAPPER = new ObjectMapper() .registerModule(new JavaTimeModule())
Deep-copying objects via Jackson serialization
serialization
deep-copy
generics
Intermediate
7 steps
ruby
module DeepImmutable module_function def deep_freeze(obj)
Deep-freezing config with recursive immutability
immutability
recursion
deep-copy
Intermediate
8 steps
php
<?php namespace App\Services;
Tagged cache invalidation in Laravel
caching
cache-tags
invalidation
Intermediate
5 steps
java
package com.example.time; import java.time.Duration; import java.time.Instant;
Adding ISO-8601 durations across time zones in Java
date-time
iso-8601
parsing
Intermediate
7 steps
php
final class BitmapGrid { private SplFixedArray $cells;
A flat-array bitmap grid in PHP
data-structures
row-major-order
bitmap
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/compiling-route-patterns-into-regex-in-php-explained-php-3606/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.