/greppy

:scroll: Relax with this awesome library for working with regular expressions with PHP

Primary LanguagePHPMIT LicenseMIT

Greppy

Deprecation Notice

Greppy is going to be phased away in favor of the PHPVerbalExpressions project.

Build Status Scrutinizer Code Quality Latest Unstable Version License SensioLabsInsight

Why use Greppy?

  • Isolate your regex patterns and matching so they can be easily mocked inside unit tests
  • Represent important and recurrent patterns with custom pattern classes
  • Write more human-readable regular expressions with a fluent API using the FluentPattern object.

Feature Guide

Bootstrap

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

Custom pattern objects

With Greppy, you can define pattern objects – types – to easily define, reuse and maintain common patterns used in web applications.

If you use regex to match domain, for instance, instead of doing:

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

You may define a DomainPattern type, such as:

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+)?/?/";
    }
}

And use it like this:

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

The predefined Pattern object

Matching any single character

The PHP way:

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

The Greppy way:

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

Matching any digit

The PHP way:

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

The Greppy way:

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

Matching a literal

The PHP way:

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

The Greppy way:

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

Matching a group of literals

The PHP way:

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

The Greppy way:

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

Matching a range

The PHP way:

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

The Greppy way:

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

Matching a repetition

The PHP way:

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

The Greppy way:

$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