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
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 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.