relaxphp/greppy

使用这个令人惊叹的库,在PHP中处理正则表达式,放松心情

dev-master 2016-03-20 10:58 UTC

This package is not auto-updated.

Last update: 2024-09-25 12:37:48 UTC


README

弃用通知

Greppy 将逐步淘汰,以支持 PHPVerbalExpressions 项目。

Build Status Scrutinizer Code Quality Latest Unstable Version License SensioLabsInsight

为什么使用 Greppy?

  • 隔离正则表达式模式及匹配,以便在单元测试中轻松模拟
  • 使用自定义模式类表示重要且频繁出现的模式
  • 使用 FluentPattern 对象通过流畅的 API 编写更易读的正则表达式。

功能指南

引导

$p = new Relax\Greppy\Pattern();

自定义模式对象

使用 Greppy,您可以定义模式对象(类型),以便轻松定义、重用和维护在 Web 应用程序中使用的常见模式。

如果您使用正则表达式匹配域名,例如,而不是这样做

preg_match("/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i", $subject);

您可能定义一个 DomainPattern 类型,例如

namespace Your\Namespace;

use Relax\Greppy\Pattern;

class DomainPattern implements Pattern
{
    public function __toString()
    {
        return "/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/";
    }
}

然后这样使用它

$domain = new Your\Namespace\DomainPattern();
$m = new Relax\Greppy\SimpleMatcher("http://www.google.com");
$m->caseless()->matches($domain); // true

预定义的模式对象

匹配任何单个字符

PHP 方式

preg_match("/./", "any"); // 1

Greppy 方式

$m = new Relax\Greppy\SimpleMatcher("any");
$m->matches($p->any()); // true

匹配任何数字

PHP 方式

preg_match("/\d/", "5"); // 1

Greppy 方式

$m = new Relax\Greppy\SimpleMatcher("5");
$m->matches($p->digit()); // true

匹配文本

PHP 方式

preg_match("/e/", "hey"); // 1

Greppy 方式

$m = new Relax\Greppy\SimpleMatcher("hey");
$m->matches($p->literal("e")); // true

匹配一组文本

PHP 方式

preg_match("/[abc]/", "anthem"); // 1

Greppy 方式

$m = new Relax\Greppy\SimpleMatcher("anthem");
$m->matches($p->literal("a", "b", "c")); // true

匹配范围

PHP 方式

preg_match("/[a-z]/", "any"); // 1

Greppy 方式

$m = new Relax\Greppy\SimpleMatcher("any");
$m->matches($p->range("a", "z")); // true

匹配重复

PHP 方式

preg_match("/z{3}/", "wazzzup"); // 1
preg_match("/z{2,4}/", "wazzzzup"); // 1

Greppy 方式

$m = new Relax\Greppy\SimpleMatcher("wazzzup");
$m->matches($p->repetition("z", 3)); // true

$m = new Relax\Greppy\SimpleMatcher("wazzzzup"); 
$m->matches($p->repetition("z", 2, 4)); // true