eugene-erg / regular-expression
PCRE patterns as objects: match, replace and split, and a syntax tree of a pattern (groups, lengths, round trip)
Requires
- php: ^8.3
- eugene-erg/peg-parser: ^1.0
Requires (Dev)
- laravel/pint: ^1.32
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.2
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-phpunit: ^2.1
- phpstan/phpstan-strict-rules: ^2.1
- phpunit/phpunit: ^12.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-04 07:35:31 UTC
README
PCRE patterns as objects: match, replace, filter and split with exceptions instead of preg_*'s silent
false and null, and what a pattern consists of — its syntax tree, its groups, the lengths it can match —
and random strings that match it, or not.
composer require eugene-erg/regular-expression
Matching and replacing
use EugeneErg\RegularExpression\MatchResult; use EugeneErg\RegularExpression\RegularExpression; $date = RegularExpression::fromPattern('/(?<year>\d{4})-(?<month>\d\d)/'); $match = $date->match('on 2026-12-03'); // MatchResult, or null when nothing matches $match->text(); // '2026-12' $match->offset(); // 3 $match->group('year'); // '2026' $match->groups(); // [0 => '2026-12', 'year' => '2026', 1 => '2026', 'month' => '12', 2 => '12'] $date->matches('2026-12'); // true $date->matchAll('2026-12, 2027-01'); // list<MatchResult> $date->replace('2026-12', '$2/$1'); // '12/2026' $date->replace('2026-12', fn (MatchResult $m): string => $m->group('month'), count: $count); // '12', $count = 1 $date->replace(['a' => '2026-12', 'b' => 'none'], '$1'); // ['a' => '2026', 'b' => 'none'] $date->filter(['2026-12', 'none']); // [0 => '2026-12'] (new RegularExpression(','))->split('a,b,,c', withoutEmpty: true); // ['a', 'b', 'c']
- A match holds only the groups that took part in it: an optional group that did not is missing
(
group()gives null,has()false), not''.capture()gives a group's text with its offset in bytes. - Every
preg_*error — the backtrack limit, broken UTF-8 — throwsRegularExpressionException; it is never taken for "no match". - An invalid pattern or modifier throws when the object is created.
RegularExpression::literal('a.b')is a pattern that matches exactly that text.RegularExpressionsapplies several patterns one after another, with one replacement for all or one each (strings and callbacks mixed).
The pattern, modifiers and delimiter are kept apart: new RegularExpression('a/b', 'i') is written as
/a\/b/i — the delimiter is escaped where the pattern has it unescaped. fromPattern() reads one written with
any delimiter, {…} and the other mirrored pairs too.
The syntax tree
$re = RegularExpression::fromPattern('/(?<year>\d{4})-(\d\d)?/'); $re->groups(); // [1 => 'year', 2 => null] $re->minLength(); // 5 $re->maxLength(); // 7, or null when unlimited $re->syntaxTree(); // Syntax\Nodes\Pattern, read once $re->normalize(); // the pattern written back from the tree: /(?<year>\d{4})-(\d\d)?/
The tree is made of immutable nodes (Syntax\Nodes): Alternation of Sequences of Literal, CharacterType
(\d, ., \R …), UnicodeProperty, CharacterClass (with Range, PosixClass), Quantified, Group
(capturing with number and name, non-capturing with options, atomic, branch reset, lookarounds, script runs),
Conditional, Backreference, Subroutine, Assertion, OptionSetting, Verb, Callout. Each writes itself
back with __toString() and knows its minimal and maximal length.
It covers the PCRE2 syntax PHP uses: escapes in every form (\x{…}, \o{…}, \cX, \N{U+…}, octal or
backreference by the PCRE rules), \Q…\E, classes with POSIX names, all quantifier forms, named groups in the
three syntaxes, branch reset, relative references, recursion and subroutine calls, conditionals, verbs,
callouts, start-of-pattern options, comments, and the x/xx modes — also switched on inside a pattern with
(?x). Relative references are resolved to numbers, n (no auto capture) is honoured in numbering.
- The pattern written back is canonical: comments and extended-mode spaces are dropped, escapes are
normalised (
\x41→A,a{0,}→a*,\k'n'→\k<n>), and it means the same in every mode.normalize()gives it back with the original delimiter and modifiers. - Lengths are in characters (bytes without
u). Backreferences and recursion count as 0 to unlimited;\Kand(*ACCEPT)are not taken into account. {,3}and spaces inside braces are quantifiers since PCRE2 10.43 and text before: the installed version decides, or pass one:syntaxTree('10.43').
Generating strings
use EugeneErg\RegularExpression\Generation\StringGenerator; use EugeneErg\RegularExpression\RegularExpression; RegularExpression::fromPattern('/[A-Z]\d{2,4}-(?<w>[a-z]+)=\k<w>/')->generate(); // "K738-qix=qix" $generator = new StringGenerator( maxRepetition: 3, // a+ gives 1 to 4 letters randomizer: new Random\Randomizer(new Random\Engine\Mt19937(42)), // the same strings every run ); RegularExpression::fromPattern('/\p{Cyrillic}+/u')->generate(generator: $generator);
A string the whole pattern matches: the tree is walked with random choices (a branch, a repeat count, a
character of a class), backreferences repeat what their group made, subroutine calls and recursion make the
group again, conditionals follow their condition. Characters come from printable ASCII first, then from the
rest of Latin-1 or Unicode when a class (\p{Linear_B}, [^\x00-\x7f]) allows none of those.
Lookarounds, \b, ^ and $ are checked where they stand, and a sequence that breaks one is made again;
a positive lookbehind may also write its text over the end of what came before it, so (?>.*)(?<=abcd) or
([ab])...(?<=\1)z is met at once. A branch with an end anchor that more text must follow ((\s|$) before
\w+) is not taken. (*ACCEPT) ends the subroutine call or the match it is in. Every string is matched
against the whole pattern before it is returned. A pattern no string matches as a whole (a^b, (?<=a)b,
endless recursion) throws RegularExpressionException after attempts tries, and one longer than
maxLength at once. On the PCRE2 test suite, a string is found for every one of the 1 378 patterns that some
subject of the suite matches as a whole.
Length, several strings, strings that do not match
$email = RegularExpression::fromPattern('/[a-z]+@[a-z]+\.com/'); $email->generate(minLength: 12, maxLength: 12); // "luhcy@pz.com" $email->generateMany(5); // five different addresses $email->generateNonMatching(); // "n\"bd@tjtr.ofm": an address, a little broken $email->generateMany(5, minLength: 10, matching: false); // five different non-addresses of 10 or more characters
Lengths are in characters: code points in UTF mode, bytes otherwise. With a length the walk aims at it: a length
is picked between the bounds, and branches and repeat counts are picked so the parts add up to it. Subroutine
calls and backreferences count with the lengths of their groups, so /(..)\1/ is known to make only 4
characters and asking it for 3 throws at once. On the PCRE2 test suite, every length a pattern was seen to make
was hit.
A non-matching string is most often a matching one with a character taken out, put in, changed or moved —
a near miss, the kind that finds bugs in validation — and sometimes a random one, made from characters of the
pattern and printable ASCII. A pattern that matches every string (/.*/s) throws after attempts tries.
generateMany() returns different strings; when attempts strings in a row repeat ones already found
(/a|b/ has only two), it throws and says how many it found.
Checked against PCRE
PcreConformanceTest reads the 3 000+ patterns of the PCRE2 test suite (see tests/Fixtures) as normal and as
extended patterns, and checks every one the installed PCRE compiles against PCRE itself: the groups are
PCRE's; the pattern written back compiles, reads back to itself and matches each of the suite's 6 600
subjects exactly as the original; every match is within the computed lengths.
The grammar is a PEG grammar of eugene-erg/peg-parser.
Upgrading from 1.x
| 1.x | 2.0 |
|---|---|
new RegularExpression('/', 'a', '/', RegularExpression::PCRE_CASELESS) |
new RegularExpression('a', 'i') |
RegularExpression::fromString($text) |
RegularExpression::literal($text) |
match(), matchOffsetCapture() → array |
match() → MatchResult or null |
matchAll(), matchOffsetCaptureAll() |
matchAll() → list<MatchResult> |
replace(), replaceCallback(), multiReplace…() → ResultCount |
replace($subject, string|callable) → string or array, count: by reference |
grep(new Strings(...)) |
filter([...]) |
splitOffsetCapture() → OffsetCapture |
splitWithOffsets() → Capture (text, offset) |
RegularExpressionInformation::fromPattern($p)->getGroups() |
RegularExpression::fromPattern($p)->groups() (minLength(), maxLength(), syntaxTree(), normalize()) |
$info->generate($generator, $min, $max) |
$re->generate($min, $max, $generator) |
Strings, Callables, ResultCount, ResultsCount |
plain arrays and strings |
a preg_* error: [], null or an exception |
always RegularExpressionException |
Development
composer check # pint, phpstan (level max), phpunit