weew/url-matcher

Simple url matcher and parser.

v1.1.0 2016-07-25 15:17 UTC

This package is not auto-updated.

Last update: 2024-05-09 01:17:53 UTC


README

Build Status Code Quality Test Coverage Version Licence

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']);