Skip to content

string-parser ​

Splits a string into a tree of named regions described by a small grammar: each region starts and ends at a regular expression and may contain other regions.

WARNING

Superseded by eugene-erg/peg-parser. This package gets no new features. The ecosystem no longer uses it: since 3.0 eugene-erg/icu-message-format-parser parses with peg-parser, and so does the PO formatter. A region becomes a Peg::node() between its start and end patterns; unlike this package, peg-parser also says where and why a string does not match.

bash
composer require eugene-erg/string-parser
php
use EugeneErg\StringParser\DataTransferObjects\Item;
use EugeneErg\StringParser\DataTransferObjects\Root;
use EugeneErg\StringParser\Parser;

$grammar = new Root('expr', children: [
    'group' => new Item('\(', '\)', children: [
        'group' => new Item('\(', '\)'),
    ]),
]);

$result = (new Parser())->parse($grammar, 'a (b (c)) d');
// Result('expr', [Value('expr', 'a'), Result('group', [Value('group', 'b'), Result('group', [c, )]), )]), Value('expr', 'd')])

The subject is read character by character (UTF-8). At every character the children of the current region are tried first, then its end pattern. Patterns are PCRE without delimiters, matched with the u and s flags.

Grammar ​

Root is the outer region, Item a region inside another; their options:

OptionDefaultMeaning
startPattern(Root: null, from the start)where the region begins
endPattern(Root: null, to the end)where it ends
includeStartfalsethe start is the beginning of the region's text instead of being skipped
includeEndItem true, Root falsethe end is consumed and kept as the last value of the region
savetruefalse leaves the text of the region out; null (Item) puts its values into the parent
exclude'\s'removed from every value: whitespace is left out by default
exceptionnulla value matching it throws ParseException
children[]regions that can start inside, by name

Things to know ​

  • Whitespace is removed by default (exclude: '\s'). For text, pass exclude: null.
  • includeEnd: false does not consume the end: the parent reads it again, as text or as the start of another region. a(b)c with a (…) region that excludes its end gives a, group(b), )c.
  • Escapes: a quoted string with \" ends at (?<!\\)(?:\\\\)*", a quote after an even number of backslashes. (?<!\\)" alone does not end "C:\\". The backslashes before the closing quote are in the end value, so join the values to get the text.

Errors ​

ParseException (a LogicException) says where: lineNumber, column (from 1, in characters) and offset (from 0). An unclosed region is reported where it was opened:

End pattern: (?<!\\)(?:\\\\)*" not found for "string" opened at line 2, column 9.

Development ​

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

From the README.md of EugeneErg/string-parser · composer require eugene-erg/string-parser