PHPackages                             wouterj/peg - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. wouterj/peg

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

wouterj/peg
===========

A PEG parser for PHP

237.7k6[1 PRs](https://github.com/wouterj/peg/pulls)PHP

Since Aug 10Pushed 2y ago1 watchersCompare

[ Source](https://github.com/wouterj/peg)[ Packagist](https://packagist.org/packages/wouterj/peg)[ RSS](/packages/wouterj-peg/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

PHP PEG Parser
==============

[](#php-peg-parser)

PEG is a generic [PEG parser](http://bford.info/packrat/) written in PHP. This parser allows you to write parsers using the Parsing Expression Grammar.

Installation
------------

[](#installation)

Install PEG using [Composer](https://getcomposer.org/download/):

```
$ composer require wouterj/peg
```

Usage
-----

[](#usage)

Use the `Grammar` class to specify the Parsing Expression Grammar by creating `Definition` instances:

```
use WouterJ\Peg\Grammar;
use WouterJ\Peg\Definition;

// specifies that Float is the main definition
$grammar = new Grammar('Float', [
    // matches any Digits (next definition), followed by a . (dot) and any Digits
    new Definition('Float', ['sequence', [
        ['identifier', 'Digits'],
        ['literal', '.'],
        ['identifier', 'Digits'],
    ]]),

    // matches any Digit (next definition) one or more times
    new Definition('Digits', ['repeat', ['identifier', 'Digit'], 1]),

    // matches 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9
    new Definition('Digit', ['characterClass', '0-9']),
]);
```

Use `Grammar#parse()` to parse input strings using this grammar. The return value is the part of the string that matched or `null` when there is no match:

```
// ...

echo $grammar->parse('1.2'); // 1.2
echo $grammar->parse('1039.50'); // 1039.50
echo $grammar->parse('abc'); // NULL

// please note that it doesn't have to match the full string
echo $grammar->parse('1.2a'); // 1.2
```

### Using the PEG syntax

[](#using-the-peg-syntax)

Of course, using arrays to define the grammar is really ugly. This is why PEG comes with `PegGrammar`, a parser that is able to parse PEG syntax. It returns a ready to use grammar instance using the parsed grammar.

```
use WouterJ\Peg\PegGrammar;

$pegGrammar = new PegGrammar();

// our float parser (equal to the previous one)
$grammar = $pegGrammar->parse(
