codekandis / regular-expressions
`codekandis/regular-expressions` 是一个提供正则表达式接口和类的库。
Requires
- php: ^7.4
Requires (Dev)
- codekandis/phpunit: ^3
- roave/security-advisories: dev-master
This package is auto-updated.
Last update: 2024-09-05 20:17:02 UTC
README
codekandis/regular-expressions 是一个提供正则表达式接口和类的库。
索引
安装
使用以下命令安装最新版本:
$ composer require codekandis/regular-expressions
测试
使用以下命令测试代码:
$ composer test
如何使用
RegularExpression 包装了几个 PHP RegEx 函数。有关各参数的描述,请参阅相关方法描述中链接的 PHP 手册。以下是对参数 [$throwNoMatchException][] 的描述
实例化
必须将模式传递给 RegularExpression 的构造函数。
$regularExpression = new RegularExpression( '~[a-z]+[0-9]+~' );
如果传递的模式无效,将抛出 InvalidRegularExpressionException。
RegularExpression::match()
RegularExpression::match() 包装了 PHP 的函数 preg_match()。
$regularExpression = new RegularExpression( '~[a-z]+[0-9]+~' ); $match = $regularExpression->match( 'foo01234_bar56789' ); /** * $match = [ * 'foo01234' * ] */
此方法提供了一个参数 $throwNoMatchException。默认为 true。如果正则表达式不匹配主题,将抛出 RegularExpressionNotMatchingException。如果将参数 $throwNoMatchException 设置为 false,则方法返回 null。
传递无效的偏移量将抛出 InvalidOffsetException。
RegularExpression::matchAll()
RegularExpression::matchAll() 包装了 PHP 的函数 preg_match_all()。
$regularExpression = new RegularExpression( '~[a-z]+[0-9]+~' ); $matches = $regularExpression->matchAll( 'foo01234_bar56789' ); /** * $matches = [ * [ * 'foo01234', * 'bar56789' * ] * ] */
此方法提供了一个参数 $throwNoMatchException。默认为 true。如果正则表达式不匹配主题,将抛出 RegularExpressionNotMatchingException。如果将参数 $throwNoMatchException 设置为 false,则方法返回 null。
传递无效的偏移量将抛出 InvalidOffsetException。
RegularExpression::replace()
RegularExpression::replace() 包装了 PHP 的函数 preg_replace()。
$regularExpression = new RegularExpression( '~[a-z]+[0-9]+~' ); $replacedSubject = $regularExpression->replace( 'foo01234_bar56789', 'replacement' ); /** * $replacedSubject = 'replacement_replacement' */
此方法提供了一个参数 $throwNoMatchException。默认为 true。如果正则表达式不匹配主题,将抛出 RegularExpressionNotMatchingException。如果将参数 $throwNoMatchException 设置为 false,则方法返回传递的主题。
传递无效的限制将抛出 InvalidLimitException。