PHP code example of bentools / url-pattern

1. Go to this page and download the library: Download bentools/url-pattern library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bentools / url-pattern example snippets


use BenTools\UrlPattern\URLPattern;

$pattern = new URLPattern('https://example.com/books/:id');

$pattern->test('https://example.com/books/42');   // true
$pattern->exec('https://example.com/books/42')?->pathname->groups['id']; // "42"
$pattern->test('foo');                              // false (never throws on invalid URLs)

use BenTools\UrlPattern\URLPattern;

// From a constructor string
$pattern = new URLPattern('https://*.example.com/books/:id(\\d+)');

// From a constructor string, relative to a base URL
$pattern = new URLPattern('/books/:id', 'https://example.com');

// From component patterns (missing components default to the "*" wildcard)
$pattern = new URLPattern(['hostname' => '{*.}?example.com', 'pathname' => '/books/:id']);

// With options
$pattern = new URLPattern('https://example.com/Books/:id', options: ['ignoreCase' => true]);

$pattern = new URLPattern('https://example.com/books/:id');

$pattern->protocol;        // "https"
$pattern->username;        // "*"
$pattern->password;        // "*"
$pattern->hostname;        // "example.com"
$pattern->port;            // ""
$pattern->pathname;        // "/books/:id"
$pattern->search;          // "*"
$pattern->hash;            // "*"
$pattern->hasRegExpGroups; // false

$pattern = new URLPattern(['pathname' => '/books/:id/:section?']);

$pattern->test('https://example.com/books/42');                // true
$pattern->test('/books/42/reviews', 'https://example.com');    // true
$pattern->test(['pathname' => '/books/42']);                   // true
$pattern->test('not a url');                                   // false

$result = $pattern->exec('https://example.com/books/42');
$result->inputs;                      // ["https://example.com/books/42"]
$result->pathname->input;             // "/books/42"
$result->pathname->groups;            // ["id" => "42", "section" => null]
$result->hostname->groups;            // [0 => "example.com"] (anonymous wildcard group)