weew / url-matcher
Simple url matcher and parser.
Installs: 45 991
Dependents: 2
Suggesters: 0
Security: 0
Stars: 1
Watchers: 2
Forks: 2
Open Issues: 0
Requires
- weew/collections: ^1.0
- weew/helpers-array: ^1.0
- weew/helpers-string: ^1.2
Requires (Dev)
- phpunit/phpunit: ^4.7
- satooshi/php-coveralls: ^0.6.1
This package is not auto-updated.
Last update: 2024-11-07 03:58:35 UTC
README
Table of contents
Installation
composer require weew/url-matcher
Introduction
This this simple matcher allows you to match url like paths against patterns with placeholders and even extract them.
Usage
Creating a new matcher is very simple.
$matcher = new UrlMatcher();
Matching
Below is a very basic matching example.
// true $matcher->match('users/{id}', 'users/1'); // false $matcher->match('users/{id}', 'users');
Placeholders can be optional by adding ?
at the end.
// true $matcher->match('users/{id?}', 'users/1'); // true $matcher->match('users/{id?}', 'users');
Placeholders can have custom patterns.
$matcher->addPattern('id', '[0-9]+'); // true $matcher->match('users/{id}', 'users/1'); // false $matcher->match('users/{id}', 'users/abc');
You can provide patterns inline.
// true $matcher->match('users/{id}', 'users/1', [ 'id' => '[0-9]+', ]);
Placeholders can be optional too.
// 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
.
$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.
$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.
// api.service.com $matcher->replace('{subdomain}.service.com', 'subdomain', 'api'); // api.service.com/v1 $matcher->replaceAll('{subdomain}.service.com/{version}', ['subdomain' => 'api', 'version' => 'v1']);