The PathToRegexp
PHP library allows you to easily convert route paths into regular expression patterns for flexible route matching in web applications. This readme provides an overview of the library and includes various examples of usage.
composer require diego03/path-to-regexp
use Diego\PathToRegexp\PathParser;
$pathParser = new PathParser();
$pattern = $pathParser->toRegex('/users/:id/edit');
// Use $pattern in your route matching logic
if ($pattern->match($uri)) {
// Matched!
}
$pathParser = new PathParser();
$pattern = $pathParser->toRegex('/posts/:postId');
// The resulting pattern will match paths like '/posts/123'
if ($pattern->match($uri)) {
// Matched!
}
$pathParser = new PathParser();
$pattern = $pathParser->toRegex('/articles/:slug?');
// The resulting pattern will match paths like '/articles' and '/articles/some-slug'
if ($pattern->match($uri)) {
// Matched!
}
$pathParser = new PathParser();
$pattern = $pathParser->toRegex('/categories/:categoryName');
// The resulting pattern will match paths like '/categories/some-category'
if ($pattern->match($uri)) {
// Matched!
}
$pathParser = new PathParser();
$pattern = $pathParser->toRegex('/users/:userId/:action?');
// The resulting pattern will match paths like '/users/123' and '/users/123/edit'
if ($pattern->match($uri)) {
// Matched!
}
The library uses the TRegx\CleanRegex\Pattern
class for regular expression patterns. You can leverage its features for more advanced use cases. Check the T-Regx documentation for detailed information.
Contributions are welcome! Feel free to open issues or submit pull requests.
This library is open-sourced software licensed under the MIT license.