Search by

eugene-erg / peg-parser

EugeneErg

Parsing expression grammars (PEG) for PHP: PCRE terminals, ordered choice, lookahead, named nodes and tokens, errors with line and column

Package info

github.com/EugeneErg/peg-parser

pkg:composer/eugene-erg/peg-parser

Statistics

Installs: 83

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

1.0.0 2026-12-03 13:18 UTC

This package is auto-updated.

Last update: 2026-12-03 13:19:58 UTC


README

Parsing expression grammars (PEG) for PHP. A grammar is a set of named rules built from a few expressions; the parser turns a string into a tree of named nodes and tokens, or says where and why it does not match. It is the parser of eugene-erg/icu-message-format-parser.

composer require eugene-erg/peg-parser
use EugeneErg\PegParser\Grammar;
use EugeneErg\PegParser\Parser;
use EugeneErg\PegParser\Peg;

$grammar = new Grammar(
    rules: [
        'message' => Peg::many(Peg::choice(Peg::ref('argument'), Peg::token('text', Peg::pattern('[^{]++')))),
        'argument' => Peg::node('argument', '{', Peg::token('name', Peg::pattern('\w+')), '}'),
    ],
    start: 'message',
);

$tree = (new Parser($grammar))->parse('Hello, {name}!');
// Node('message', [Token('text', 'Hello, '), Node('argument', [Token('name', 'name')]), Token('text', '!')])

Expressions

Peg:: PEG Matches
literal('ab'), or just 'ab' "ab" exactly this text
pattern('[a-z]+', flags: 'i') a PCRE pattern at the current place (anchored with \G, flag u always on)
any() . one character
seq(a, b) a b a, then b
choice(a, b) a / b the first that matches: ordered, no ambiguity
many(a) / some(a) / optional(a) a* / a+ / a? as many as possible (greedy, no backtracking into it)
repeat(a, 2, 5) a{2,5} from 2 to 5 times
and(a) / not(a) &a / !a checks what follows without consuming it
end() !. the end of the subject
empty() ε nothing, always matches
ref('rule') rule a rule of the grammar, so rules can be recursive

Wherever an expression is expected, a string is a literal; several expressions in many(), optional(), node() and the like are a sequence.

The tree

Only two expressions produce output, everything else is syntax:

  • Peg::node('name', …) — a Node with the nodes and tokens found inside, the matched text and offset; get('name') and all('name') find children.
  • Peg::token('name', expression, value: null) — a Token with the matched text, or value if given (Peg::token('quote', "''", "'")). For a pattern, its named groups are in $token->groups: Peg::token('range', Peg::pattern('\{(?<from>\d+),(?<to>\d+)\}')).

parse() returns a Node named after the start rule. The whole subject must match. matches() only says whether it does.

Errors

ParseException (a LogicException) points at the furthest place the parser reached and lists what it expected there:

Unexpected end of input at line 2, column 30, expected an option key or "}".

It has lineNumber, column (from 1, in characters), offset (from 0, in characters), byteOffset and expected. Name an expression for errors with Peg::expected('an option key', …): then the description is reported instead of the patterns inside it.

Mistakes in the grammar are GrammarException, thrown at once: a pattern that does not compile, an unknown rule, an empty literal, left recursion (e = e "+" a), and a pattern that hits a PCRE limit while matching — it is never taken for "does not match".

Speed

Every pattern is one preg_match() at an offset, so a long run of text is read in one step: the parse is linear in the length of the subject. A million characters of text and arguments take a few hundred milliseconds, plain text alone a few milliseconds.

  • Write long runs with possessive quantifiers: [^'{]*+(?:'(?!\{)[^'{]*+)*+ rather than (?:[^'{]|'(?!\{))+. The second repeats a group per character and runs out of the PCRE JIT stack on long input (you get a GrammarException, not a wrong result).
  • choice() backtracks: an alternative that fails late is matched again by the next one. When a grammar backtracks a lot, new Grammar(…, memoize: true) remembers every rule result by offset (packrat parsing): linear time on any grammar, at the cost of memory.

Development

composer check   # pint, phpstan (level max), phpunit