Url matcher
, (*1)
Table of contents
Installation
composer require weew/url-matcher
, (*2)
Introduction
This this simple matcher allows you to match url like paths against patterns with placeholders and even extract them., (*3)
Usage
Creating a new matcher is very simple., (*4)
$matcher = new UrlMatcher();
Matching
Below is a very basic matching example., (*5)
// true
$matcher->match('users/{id}', 'users/1');
// false
$matcher->match('users/{id}', 'users');
Placeholders can be optional by adding ?
at the end., (*6)
// true
$matcher->match('users/{id?}', 'users/1');
// true
$matcher->match('users/{id?}', 'users');
Placeholders can have custom patterns., (*7)
$matcher->addPattern('id', '[0-9]+');
// true
$matcher->match('users/{id}', 'users/1');
// false
$matcher->match('users/{id}', 'users/abc');
You can provide patterns inline., (*8)
// true
$matcher->match('users/{id}', 'users/1', [
'id' => '[0-9]+',
]);
Placeholders can be optional too., (*9)
// true
$matcher->match('users/{id?}', 'users/1', [
'id' => '[0-9]+',
]);
// true
$matcher->match('users/{id?}', 'users', [
'id' => '[0-9]+',
]);
Parsing
Extracting placeholders is very trivial too. The parse
method always returns an instance of IDictionary
., (*10)
$dictionary = $matcher->parse('users/{id}', 'users/123');
// 123
$dictionary->get('id');
$dictionary = $matcher->parse('users/{id}', 'users');
// null
$dictionary->get('id');
Of course, placeholders can have custom patterns., (*11)
$matcher->addPattern('id', '[0-9]+');
$dictionary = $matcher->parse('users/{id}', 'users/123');
// 123
$dictionary->get('id');
$dictionary = $matcher->parse('users/{id}', 'users/abc');
// null
$dictionary->get('id');
Replacing
You can do the opposite of parsing by replacing placeholders with specific values., (*12)
// api.service.com
$matcher->replace('{subdomain}.service.com', 'subdomain', 'api');
// api.service.com/v1
$matcher->replaceAll('{subdomain}.service.com/{version}', ['subdomain' => 'api', 'version' => 'v1']);