PHP 8.4+ implementation of the URL Pattern API Web API standard.
composer require craftcms/url-patternuse UrlPattern\URLPattern;
// Create a pattern
$pattern = new URLPattern(['pathname' => '/books/:id']);
// Test if a URL matches
if ($pattern->test('https://example.com/books/123')) {
echo "Match!";
}
// Get match results with captured groups
$result = $pattern->exec('https://example.com/books/123');
echo $result->pathname->groups->id; // "123"The pattern syntax supports:
- Literal strings:
/books- matches exactly - Named groups:
/books/:id- captures the id - Wildcards:
/posts/*- matches any characters - Regex groups:
/books/(\\d+)- matches digits only - Optional groups:
/product/:action?- optional segment - Repeated groups:
/product/:action+- one or more,/product/:action*- zero or more - Non-capturing groups:
/product{/}?- optional literal text
// Pattern with base URL
$pattern = new URLPattern('/books/:id', 'https://example.com');
// Full URL pattern
$pattern = new URLPattern('https://example.com/books/:id');
// Component-based pattern
$pattern = new URLPattern([
'protocol' => 'http{s}?',
'hostname' => '{:subdomain.}*example.com',
'pathname' => '/books/:id',
]);composer test# Run all checks (lint + PHPStan + tests)
composer check
# Lint code
composer lint
# Auto-fix lint issues
composer fix
# Static analysis
composer phpstanMIT