Skip to content

craftcms/url-pattern-php

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

URL Pattern API for PHP

PHP 8.4+ implementation of the URL Pattern API Web API standard.

Installation

composer require craftcms/url-pattern

Usage

Basic Usage

use 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"

Pattern Syntax

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

Full URL Patterns

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

Testing

composer test

Code Quality

# Run all checks (lint + PHPStan + tests)
composer check

# Lint code
composer lint

# Auto-fix lint issues
composer fix

# Static analysis
composer phpstan

License

MIT

About

No description, website, or topics provided.

Resources

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages