PHP code example of mnavarrocarter / path-to-regexp-php

1. Go to this page and download the library: Download mnavarrocarter/path-to-regexp-php 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/ */

    

mnavarrocarter / path-to-regexp-php example snippets


use MNC\PathToRegExpPHP\PathRegExpFactory;

$pathRegex = PathRegExpFactory::create('/user/:name');
$result = $pathRegex->match('/user/john');
$result->getMatchedString();    // '/user/john'
$result->getValues();           // ['name' => 'john']

use MNC\PathToRegExpPHP\PathRegExpFactory;

$pathRegex = PathRegExpFactory::create('/:foo/:bar');
$pathRegex->getParts()[0]->getName(); // 'foo'
$pathRegex->getParts()[1]->getName(); // 'bar'

$result = $pathRegex->match('/test/route');
$result->getMatchedString();    // '/test/route'
$result->getValues();           // ['foo' => 'test', 'bar' => 'route']

use MNC\PathToRegExpPHP\PathRegExpFactory;

$pathRegex = PathRegExpFactory::create('/:foo/:bar?');

$result = $pathRegex->match('/test');
$result->getMatchedString();    // '/test'
$result->getValues();           // ['foo' => 'test', 'bar' => null]

$result = $pathRegex->match('/test/route');
$result->getMatchedString();    // '/test/route'
$result->getValues();           // ['foo' => 'test', 'bar' => 'route']

use MNC\PathToRegExpPHP\PathRegExpFactory;

$pathRegex = PathRegExpFactory::create('/:foo*');

$result = $pathRegex->match('/');
$result->getMatchedString();    // '/'
$result->getValues();           // ['foo' => null];

$result = $pathRegex->match('/bar/baz');
$result->getMatchedString();    // '/bar/baz'
$result->getValues();           // ['foo' => 'bar/baz']

use MNC\PathToRegExpPHP\PathRegExpFactory;

$pathRegex = PathRegExpFactory::create('/:foo+');

$pathRegex->match('/'); // Will throw NoMatchException

$result = $pathRegex->match('/bar/baz');
$result->getMatchedString();    // '/bar/baz'
$result->getValues();           // ['foo' => 'bar/baz']

use MNC\PathToRegExpPHP\PathRegExpFactory;

$pathRegex = PathRegExpFactory::create('/:foo(\\d+)');

$result = $pathRegex->match('/123');
$result->getMatchedString();    // '/123'
$result->getValues();           // ['foo' => '123']

$pathRegex->match('/abc'); // Will throw a NoMatchException

use MNC\PathToRegExpPHP\PathRegExpFactory;

$pathRegex = PathRegExpFactory::create('/:foo/(.*)');

$result = $pathRegex->match('/test/route');
$result->getMatchedString();   // '/test/route'
$result->getValues();          // ['foo' => 'test', '0' => 'route']