简单的面向对象正则表达式外观

1.0.1 2018-12-12 13:04 UTC

This package is auto-updated.

Last update: 2024-09-13 03:11:19 UTC


README

这是一个简单的面向对象外观,用于PHP内置的PCRE正则表达式函数。

<?php
$matcher = new Matcher();
$regexp = new Regexp("(exam)ple");

$match = $matcher->match($regexp, "An example string");
$match->getSubject(); //"An example string"
$match->getMatch(); //"example"
$match->getOffset(); //3
$match->getGroups()[0]->getMatch(); //"exam"

目录

安装

composer require jeroenvanderlaan/regexp

描述

这个库旨在使PHP中的正则表达式更容易处理。它使匹配代码更易于阅读,并允许利用面向对象的好处,如依赖注入和改进的可测试性。

我最初编写这个库是为了快速开发多个用于个人使用的模式匹配工具。它使我能够快速编写独立的测试,并重用大部分代码库来实现类似但略有不同的命令行工具。此外,它还可以通过临时标记替换来绕过复杂的递归模式匹配。

话虽如此,这个库并没有针对性能进行优化,不应在大规模生产应用中使用。如果您喜欢,可以在开发期间使用它,但请确保将其封装在接口中,并在进入生产后用您自己的更高效实现替换这个库。

使用

匹配

匹配器可以匹配正则表达式的第一个出现,或者匹配所有出现。

<?php
$matcher = new Matcher();
$regexp = new Regexp("foo|bar");

$match = $matcher->match($regexp, "foobar");
$match->getSubject(); //"foobar"
$match->getMatch(); //"foo"
$match->getOffset(); //0

$matches = $matcher->matchAll($regexp, "foobar");
$match = array_pop($matches);
$match->getSubject(); //foobar
$match->getMatch(); //bar
$match->getOffset(); //3

替换

替换器使用替换回调函数替换正则表达式的所有出现。

<?php
$replacer = new Replacer();
$regexp = new Regexp("foo|bar");
$callback = function (string $match) {
	return strrev($match);
};

$replaced = $replacer->replace($regexp, "foobar", $callback);
(string) $replaced; //oofrab

替换器返回一个对象,除了替换的字符串外,还包含原始字符串的引用和一个包含Replacement对象的数组。

<?php
$replaced->getReplacedString(); //oofrab
$replaced->getOriginalString(); //foobar
$replacements = $replaced->getReplacements();
$replacements[0]->getMatch(); //foo
$replacements[0]->getReplacement(); //oof
$replacements[1]->getMatch(); //bar
$replacements[1]->getReplacement(); //rab

反转替换

Replacement对象允许您撤销字符串替换。

<?php
$unreplacer = new Unreplacer();
$unreplacer->unreplace("rab", ...$replacements); //returns "bar"
$unreplacer->unreplace("oofrabbaz", ...$replacements); //returns foobarbaz

替换

替换器允许用(临时)随机字符串替换非字母数字字符。

如果您想递归匹配但又不情愿编写复杂的正则表达式,这将很有用。

<?php
$substitutor = new Substitutor();
$regexp = new Regexp("\<\>");
$substituted = $substitutor->substitute($regexp, "<foo></foo>"); //substitutes all "<" and ">"
$matcher->match($regexp, (string) $substituted); //returns null

您可以用与替换相同的方式撤销替换。

<?php
$substitutes = $substituted->getReplacements();
$unreplacer = new Unreplacer();
$unreplaced = $unreplacer->unreplace((string) $substituted, ...$substitutes);
//unreplaced is now "<foo></foo>"