Easy regular expression building
PHP
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
src/MarkWilson
.gitignore
LICENSE.txt
README.md
composer.json
phpunit.xml

README.md

VerbalExpressionsPhp

PHP port of jehna/VerbalExpressions.

Installation

Composer

Add to composer.json:-

{
    "require": {
        ...,
        "markwilson/verbal-expressions-php": "dev-master"
    }
}

Example usage

<?php

require_once 'vendor/autoload.php';

use MarkWilson\VerbalExpression;
use MarkWilson\VerbalExpression\Matcher;

// initialise verbal expression instance
$verbalExpression = new VerbalExpression();

// URL matcher
$verbalExpression->startOfLine()
                 ->then('http')
                 ->maybe('s')
                 ->then('://')
                 ->maybe('www.')
                 ->anythingBut(' ')
                 ->endOfLine();

// compile expression - returns ^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$
$verbalExpression->compile();

// perform match
preg_match($verbalExpression, 'http://www.google.com'); // returns 1
// or
$matcher = new Matcher();
$matcher->isMatch($verbalExpression, 'http://www.google.com'); // returns true

Nesting expressions

<?php

$innerExpression = new VerbalExpression();
$innerExpression->word();

$outerExpression = new VerbalExpression();
$outerExpression->startOfLine()
                ->find($innerExpression)
                ->then($innerExpression)
                ->endOfLine();

// returns ^(\w+)(\w+)$
$outerExpression->compile();

Disable sub pattern capturing

By default, sub patterns are captured and will be returned in the matches array.

<?php

// disable sub pattern capture
$verbalExpression->disableSubPatternCapture()->word(); // (?:\w+)
// or
$verbalExpression->word(false); // (?:\w+)

Disabling this will only affect subsequent additions to the expression; any already added will be unaffected. This allows for disabling and enabling in groups.

<?php

// equivalent to (\w+)(?:\w+)(?:\w+)(\w+)
$verbalExpression->word()
                 ->disableSubPatternCapture()
                 ->word()
                 ->word()
                 ->enableSubPatternCapture()
                 ->word();