gpolguere / path-to-regexp-php
https://github.com/component/path-to-regexp 的 PHP 版本
dev-master
2018-12-12 21:52 UTC
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2024-09-28 15:34:13 UTC
README
将 Express 风格的路径字符串(如 /user/:name
)转换为正则表达式。
这是 JS 库 component/path-to-regexp pillarjs/path-to-regexp 的 PHP 版本,不包含对 JS 原生正则表达式的支持(无法检查路径的使用情况)。
用法
require_once "PathToRegexp.php"; PathToRegexp::convert($path, $keys, $options);
- path 以 express 格式表示的字符串、字符串数组或正则表达式。
- keys 一个数组,用于填充 URL 中存在的键。
- 选项
- options.sensitive 当设置为
true
时,路由将区分大小写。 - options.strict 当设置为
true
时,路径末尾允许有斜线。 - options.end 当设置为
false
时,路径将在开始处匹配。
- options.sensitive 当设置为
$keys = []; $re = PathToRegexp::convert('/foo/:bar', $keys); // $re = '/^\/foo\/([^\/]+?)\/?$/i' // $keys = array(array("name" => 'bar', "delimiter" => '/', "repeat" => false, "optional" => false))
参数
路径可以定义参数并自动填充键数组。
命名参数
命名参数通过在参数名前加冒号(:foo
)来定义。默认情况下,此参数将匹配到下一个路径段。
$re = PathToRegexp::convert('/:foo/:bar', $keys); // $keys = array(array("name" => 'foo', ... ), array("name" => 'bar', ... )) $matches = PathToRegexp::match($re, '/test/route'); // $matches = array('/test/route', 'test', 'route')
后缀参数
可选
参数可以通过在末尾加上问号(?
)来使整个参数可选。这也将使任何前缀路径分隔符(/
或 .
)也变为可选。
$re = PathToRegexp::convert('/:foo/:bar?', $keys); // $keys = array(array("name" => 'foo', ... ), array("name" => 'bar', "delimiter" => '/', "optional" => true, "repeat" => false )) $matches = PathToRegexp::match($re, '/test'); // $matches = array('/test', 'test', null) $matches = PathToRegexp::match($re, '/test/route'); // $matches = array('/test', 'test', 'route')
零个或多个
参数可以通过在末尾加上星号(*
)来表示零个或多个参数匹配。匹配时也会考虑前缀路径分隔符。
$re = PathToRegexp::convert('/:foo*', $keys); // $keys = array(array("name" => 'foo', "delimiter" => '/', "optional" => true, "repeat" => true)) $matches = PathToRegexp::match($re, '/'); // $matches = array('/', null) $matches = PathToRegexp::match($re, '/bar/baz'); // $matches = array('/bar/baz', 'bar/baz')
一个或多个
参数可以通过在末尾加上加号(+
)来表示一个或多个参数匹配。匹配时包括前缀路径分隔符。
$re = PathToRegexp::convert('/:foo+', $keys); // $keys = array(array("name" => 'foo', "delimiter" => '/', "optional" => false, "repeat" => true)) $matches = PathToRegexp::match($re, '/'); // $matches = null $matches = PathToRegexp::match($re, '/bar/baz'); // $matches = array('/bar/baz', 'bar/baz')
自定义匹配参数
所有参数都可以提供一个自定义的匹配正则表达式并覆盖默认值。请注意:字符串中的反斜杠需要转义。
$re = PathToRegexp::convert('/:foo(\\d+)', $keys); // $keys = array(array("name" => 'foo', ... )) $matches = PathToRegexp::match($re, '/123'); // $matches = array('/123', '123') $matches = PathToRegexp::match($re, '/abc'); // $matches = null
未命名参数
可以编写一个未命名的参数,它仅是匹配组。它的工作方式与命名参数相同,但将按数字索引。
$re = PathToRegexp::convert('/:foo/(.*)', $keys); // $keys = array(array("name" => 'foo', ... ), array("name": '0', ... )) $matches = PathToRegexp::match($re, '/test/route'); // $matches = array('/test/route', 'test', 'route')
许可
MIT