shroophp/pattern

A library for simple pattern matching.

v1.0.4 2018-12-05 23:39 UTC

This package is auto-updated.

Last update: 2024-11-08 23:30:36 UTC


README

A library for simple pattern matching.

Installation

composer require 'shroophp/pattern ^1.0'

Example Usage

By default, patterns will be interpreted using a simple curly-brace syntax. Each key specified within curly-braces will equate to a lazy regular expression group (i.e. (.*?)).

<?php

use ShrooPHP\Pattern\Interpreter;

require 'vendor/autoload.php';

$interpreter = new Interpreter;
$pattern = $interpreter->interpret('Hello, {subject}!');

$world = $pattern->match('Hello, world!'); // array('subject' => 'world')
$mismatch = $pattern->match('Goodbye, galaxy!'); // null

Tokens other than curly-braces may be used by passing them to the constructor of the interpreter.

<?php

use ShrooPHP\Pattern\Interpreter;

require 'vendor/autoload.php';

$interpreter = new Interpreter('(', ')');
$curly = $interpreter->interpret('{greeting}, {subject}!');

$mismatch = $curly->match('Hello, world!'); // null
$exact = $curly->match('{greeting}, {subject}!'); // array()

$round = $interpreter->interpret('(greeting), (subject)!');
$matched = $round->match('Hello, world!'); // array(
                                           //   'greeting' => 'Hello',
                                           //    'subject' => 'world'
                                           // )

By default, tokens may be escaped using a backslash (i.e. \).

<?php

use ShrooPHP\Pattern\Interpreter;

require 'vendor/autoload.php';

$interpreter = new Interpreter;
$pattern = $interpreter->interpret('\{{key\}}');

$matched = $pattern->match('{value}'); // array('key}' => 'value}')