Regex Logic & Automata Solver
Installation
composer config minimum-stability dev
composer config prefer-stable true
composer require php-regex/regex-automata:2.x-devThe vendor/bin/regex commands on this page come from the CLI (composer require --dev php-regex/regex-cli), while the PHP API lives in php-regex/regex-automata, PHP 8.1+ with ext-mbstring.
The Concept
PHPRegex can transform a regex into a deterministic finite automaton (DFA). That means a pattern becomes a set of strings, and comparisons become precise set operations instead of guesswork.
Verified example (intersection):
vendor/bin/regex compare '/edit/' '/[a-z]+/'
FAIL Conflict detected!
Example: "edit"
Use Case 1: Route Conflict Detection (The “Intersection” Problem)
Route A is /order/\d+ and Route B is /order/[a-z0-9]+. They look different, but can they match the same string?
Command:
vendor/bin/regex compare '/order\/\d+/' '/order\/[a-z0-9]+/'
Result:
FAIL Conflict detected!
Example: "order/0"
Interpretation: conflict detected on input order/0.
Intersection asks “is there a string that matches BOTH patterns?” If the answer is yes, your routes can shadow each other.
Use Case 2: Security Audits (The “Subset” Problem)
A security policy allows [a-zA-Z0-9]+. A developer writes \w+, which includes _ and might be forbidden.
Command:
vendor/bin/regex compare '/\w+/' '/[a-zA-Z0-9]+/' --method=subset
Result:
FAIL Pattern 1 allows strings that Pattern 2 forbids.
Counter-example: "_"
Interpretation: FAIL. Counter-example: _.
Subset asks “does pattern 1 allow ONLY what pattern 2 allows?” If not, the counter-example shows the exact violation.
Use Case 3: Safe Refactoring (The “Equivalence” Problem)
You want to simplify [0-9] to \d and prove it is safe.
Command:
vendor/bin/regex compare '/[0-9]+/' '/\d+/' --method=equivalence
Result:
PASS Patterns are mathematically equivalent.
Equivalence asks “do these patterns accept the exact same set of strings?”
Use Case 4: Rewrites that Keep $matches (The “Match Equivalence” Problem)
Two patterns match the same strings, yet one replaces the other only if
preg_match() writes the same $matches for them. PCRE takes the first alternative that
leads to a match, not the longest: on ab, /a|ab/ matches a and /ab|a/ matches ab.
$solver = new LanguageSolver();
$solver->equivalent('/(a|ab)/', '/(ab|a)/')->isEquivalent; // true: same strings
$result = $solver->matchEquivalent('/(a|ab)/', '/(ab|a)/');
$result->isEquivalent; // false
$result->counterExample; // "ab": $1 is "a", then "ab"
$solver->matchEquivalent('/a|ab/', '/a(?:b)??/')->isEquivalent; // true
Match equivalence asks “does preg_match() give the same answer,
the same match and the same groups for every subject?” The solver runs both patterns side
by side the way a leftmost-first matcher runs one, its threads in the order PCRE tries
its paths, a new start at each position until a match is found. It keeps positions only
as far as their equality goes, so the search over every subject ends, and the first
subject on which the two differ is the shortest.
It reads the fragment where that run picks the match PCRE’s backtracking picks. It refuses,
each with its reason: backreferences, conditionals and control verbs; a call that may run
its own group again ((?R), /(a(?1)?b)/), and a call that returns groups ((?1(2)));
lookarounds; atomic groups, and a possessive quantifier that could have to give back what
it matched (one whose body may match more than one way, or that something after it may
start like it does: /a++a/, /(?:ab?)++b/, \s++$); a loop over a body that can match
empty, which PCRE stops after an empty iteration; word boundaries, multiline anchors, \G
and \K; a newline convention other than \n where $ or \Z reads it, and (*CRLF)
anywhere, under which the dot reads a \r alone but not one before a \n; (*NOTEMPTY) and
(*NOTEMPTY_ATSTART), as equivalent() refuses them; an end anchor
followed by more of the pattern, another turn of the loop it stands
in included (/(?:a$)*\n/, /(?:a$)*/); an anchor, an assertion or a lookaround in a group
repeated no time, which PCRE2 still reads to choose where it tries a match (/(?:x|(?=a)){0}\w/
finds no match in "\tb", where /\w/ finds b); and two patterns of which one
reads UTF-8 and the other bytes. Groups count by number and by name: /(?<n>a)/ and /(a)/
write different $matches, and so do /(?<n>a){0}b/ and /b/, as a group repeated no time
still takes its number, and /(?(DEFINE)(?<n>x))a/ and /a/, as a group a DEFINE holds does.
Any other call of a group, (?1), (?-1), (?+1), (?&n), (?P>n) or \g<n>, runs the
body of the group where the call stands, as PCRE2 runs it from 10.30 on, older than any
release PHP bundles: the engine backtracks into the call (/(a|ab)(?1)c/ matches aabc),
the groups inside it are given back the values they held before it, and the body keeps the
options the group was written under (/(a)(?i)(?1)/ finds nothing in aA). A group a
(?(DEFINE)...) holds runs only there, under the options in force where the DEFINE stands:
/(?i:(?(DEFINE)(?<n>a)))(?&n)/ finds A. A possessive quantifier in a called group is read
wherever the group runs: /(a+b?)c(?1)d/ and /(a++b?)c(?1)d/ write the same $matches, and
so do /(?&n)c(?(DEFINE)(?<n>a+b?))/ and /(?&n)c(?(DEFINE)(?<n>a++b?))/, while
/(a++b?)c(?1)a/ is refused, as the call gives an a back to what follows it.
Neither question answers the other. The same $matches on every subject is the same
answer on every subject, so the two patterns find a match in the same subjects; it is not
the same set of whole strings, which is what equivalent() compares by default.
/a|ab/ and /a/ write the same $matches everywhere, as ab is never reached, yet
equivalent() says they differ, and they do once spliced into /^(?:…)$/. The other
way, equivalent() calls /a$/ and /a\z/ equivalent, as both match the whole string
a only, while preg_match() finds a in "a\n" with the first and nothing with the
second.
The optimizer, with verify_with_automata on as it is by default, and the lint’s suggestions put a rewrite to
matchEquivalent(): a rewrite it proves is offered, one it disproves is not. The check
works within a budget of its own (1,000 configurations, 200,000 units of work), and one that
runs out proves nothing. Where the match solver does not read a pattern, or gives up,
only a rewrite that reads as the pattern does is offered (the same normal form, as [0-9]
and \d), or one whose changed parts are each proven alone: the strings two patterns
match prove no $matches. /a(?!b)/ and /a/ match the same strings whole, yet on "ab"
only the second matches; /(?:a|ab)(?!c)/ and /(?:ab|a)(?!c)/ match "a" and "ab"
there. Two patterns read alike only when their (?(DEFINE)...) groups are written alike:
the normal form leaves out what a DEFINE holds, which only a subroutine call runs.
A changed part is proven alone when the rest of both patterns is the same and the part,
made of characters, classes, alternatives and repetitions only, matches the strings the
other matches, none of which begins another. From any position such a part ends in one
place at most, the same on both sides, whatever the pattern around it does before or after
it: /(?<!\\)(?:_|%)/ becomes /(?<!\\)[_%]/, /(?=\s*(?:,|\n))/ becomes
/(?=\s*[,\n])/, and /^\/\/\/\/x/m becomes /^\/{4}x/m. The strings the part matches
must not begin one another: /(?:a|ab)/ and /a/ write the same $matches, yet
/(?<=x)(?:a|ab)c/ finds "abc" in "xabc" and /(?<=x)ac/ nothing, as the c
backtracks into the alternation. An alternation that only lost the later copies of a
branch, \b(?:ab|cd|ab) into \b(?:ab|cd), is read branch by branch: a later copy is only
tried where an earlier one ended and what follows failed. Two runs of parts of other
counts are paired by the parts both keep: /(?<!x)-----.*-----/i and
/(?<!x)-{5}.*-{5}/i differ in each run of dashes, and each is proven alone. A part
holding a group, an anchor, a lookaround, a backreference, \K or a verb, a part inside a
lookbehind that matches strings of more than one length (what a lookbehind may hold
differs by release), and a pattern holding a subroutine call, a verb or a callout are not
proven alone. The branches at the top of a lookbehind are read together instead: the
lookbehind holds where some string one of them matches ends, whatever their order, so
/(?<![\xC2-\xDF]|[\xE0-\xEF]|[\xE0-\xEF][\x80-\xBF])/ becomes
/(?<![\xC2-\xDF\xE0-\xEF]|[\xE0-\xEF][\x80-\xBF])/ when no group stands in them and each
branch matches strings of one length on both sides, which every release accepts there.
The alternatives of a group inside the lookbehind, (?<=(?:a|bc|d)), are not its
branches: releases before PCRE2 10.43 refuse them for their two lengths. The condition of a
conditional, (?(?='|").), is not read either.
A rewrite must hold in every call the pattern may go to, not only in preg_match() from
offset 0. From an offset, ^ and \A never hold: /^[\s\S]|a/ and /^[\s\S]|b/ write
the same $matches from offset 0, yet preg_match_all() finds two matches in "xa" with
the first and one with the second. After an empty match, preg_match_all(),
preg_replace() and preg_split() try again where it stands, refusing an empty match:
/a??/ and /(?:)/ write the same $matches, yet preg_replace() gives --- and -a-
on "a". So a pattern with ^ or \A is checked again from past the start of the
subject, and one that may match empty in that retry as well, all by the match solver,
which alone models them. A pattern that reads the text before where the search starts (a
lookbehind, \b, \B, ^ under m) or that moves the start of its match (\K) is
proven by no such check, and its rewrite is offered only when it reads as the pattern
does (the same normal form, as [0-9] and \d, or a flag dropped that changes nothing),
or when each part it changed is proven alone.
The same holds for a route requirement, which the router splices into a larger pattern:
a|ab and ab|a write the same $matches anchored at both ends, yet before a b? they
capture other text.
Use Case 5: Live Input Validation (The “Prefix” Problem)
A form field checks a date as it is typed. preg_match() says 0 for 2026
and for 202a alike: neither is a whole date, and nothing tells the user which one can
still become one.
$solver = new LanguageSolver();
$solver->acceptsPrefix('/^\d{4}-\d{2}-\d{2}$/', '2026'); // true: "2026-10-03" completes it
$solver->acceptsPrefix('/^\d{4}-\d{2}-\d{2}$/', '202a'); // false: nothing does
$solver->acceptsPrefix('/^\d{4}-\d{2}-\d{2}$/', '2026-10-031'); // false: one digit too many
Prefix asks “does some string starting with this input belong to the language?” The solver reads the input on the pattern’s DFA, then asks whether an accepting state can still be reached. In UTF mode an input that ends in the middle of a character is viable when one way to finish the character is.
The Guarantee: One Engine, One Truth
Every character set the solver matches is asked from the PCRE2 that runs in your
PHP — through the normalized form (HIR) the pattern is compiled to first.
Classes and ranges, \w, \s, \d, the dot, POSIX classes, \p{...}
properties, Perl extended classes (?[ ... ]) and case-insensitive folding all
come from that one engine, never from tables the library maintains by hand.
The consequences:
- Constructs the old conversion refused outright are now answered: POSIX
classes (
[[:alpha:]], also negated[[:^digit:]]), Unicode properties (\p{L},\P{L}, scripts like\p{Greek}), extended classes ((?[ \p{L} - [aeiou] ])) and the class-set operations inside them, and the\C“one byte” escape. - Verdicts are engine-relative. A
(*UTF)start verb sets the alphabet without Unicode properties:(*UTF)\wstays ASCII, as the engine reads it. What[[:alpha:]]means under/uis what your PCRE2 says it means, and a pattern analyzed on one machine can only be compared with a pattern analyzed on the same engine. Every result says which engine answered, inpcreVersion. - Without
/uthe alphabet is bytes (0x00-0xFF); with/uit is code pointsU+0000-U+10FFFFminus the surrogate blockU+D800-U+DFFF— real subjects never contain the surrogates, so no set the solver builds does either. Counter-example strings above byte0x7Fare raw bytes, as the engine reads them. (When the code-point alphabet arrived, the sets’ shape changed once; the pinned verdicts did not.) - A pattern read as UTF-8 and one read as bytes,
(*UTF)or/uon one side only, are compared on the valid UTF-8 strings: the one read as bytes reads each character as its bytes./(*UTF)\Aé\z/and/\Aé\z/are equivalent,/(*UTF)\A.\z/and/\A.\z/differ on"\u{80}", one character and two bytes. A string that is not valid UTF-8 is not compared: under/u,preg_match()returnsfalseon it; under(*UTF)alone PHP does not check it, and PCRE2 reads it as if it were valid, with no defined answer (/(*UTF)\A.\z/matches"\xFF", which/\A.\z/urefuses).
The same engine-relative question, asked at the CLI:
vendor/bin/regex compare '/[[:alpha:]]/u' '/[a-zA-Z]/u'
FAIL Conflict detected!
Example: "A"
That only proves the languages meet — A is a letter either way. The interesting
answer is the difference, which the API hands you: on a PCRE2 built with UCP
support, [[:alpha:]] under /u is wider than the ASCII letters, and the
solver’s counter-example names a character only the POSIX side matches (ª,
for one). On an engine where it is not, the two patterns come out equivalent.
The solver follows the engine in both cases; it never guesses.
PHP API
PHPRegex\Automata\LanguageSolver is the one entry point. Each method takes two patterns (with delimiters and
flags) and optional SolverOptions, and returns a result object that carries the shortest string proving the answer:
use PHPRegex\Automata\LanguageSolver;
$solver = new LanguageSolver();
$intersection = $solver->intersection('/order\/\d+/', '/order\/[a-z0-9]+/');
$intersection->isEmpty; // false
$intersection->example; // "order/0"
$subset = $solver->subsetOf('/\w+/', '/[a-zA-Z0-9]+/');
$subset->isSubset; // false
$subset->counterExample; // "_"
$equivalence = $solver->equivalent('/[0-9]+/', '/\d+/');
$equivalence->isEquivalent; // true
$equivalence->leftOnlyExample; // null: no string only the left pattern matches
$equivalence->rightOnlyExample; // null: no string only the right pattern matches
$solver->acceptsPrefix('/^ab$/', 'a'); // true: some string starting with "a" matches
$match = $solver->matchEquivalent('/a|ab/', '/ab|a/');
$match->isEquivalent; // false: same strings, other matches
$match->counterExample; // "ab"
$dfa = $solver->compile('/[a-z]+/'); // the pattern's DFA (PHPRegex\Automata\Model\Dfa)
| method | result | answer | witness |
|---|---|---|---|
intersection($left, $right, $options = null) |
IntersectionResult |
isEmpty |
example: a string both match |
subsetOf($left, $right, $options = null) |
SubsetResult |
isSubset |
counterExample: only the left matches |
equivalent($left, $right, $options = null) |
EquivalenceResult |
isEquivalent |
leftOnlyExample, rightOnlyExample |
matchEquivalent($left, $right, $options = null) |
MatchEquivalenceResult |
isEquivalent |
counterExample: the shortest subject with other $matches |
acceptsPrefix($pattern, $input, $options = null) |
bool |
whether some string starting with $input matches |
— |
compile($pattern, $options = null) |
Dfa |
the pattern’s DFA | stored in the DFA cache when one is set |
Each of the four result objects also carries pcreVersion, the PCRE2 release
the answer was computed with ("10.49" on the engine this page’s examples ran
on). Two results with different stamps describe two engines’ languages; compare
them only knowing that.
The constructor takes the parser that reads the patterns, so they are read for its PHP and PCRE2 target, and a DFA cache that keeps compiled patterns between questions:
use PHPRegex\Automata\LanguageSolver;
use PHPRegex\Automata\Solver\InMemoryDfaCache;
use PHPRegex\Parser\RegexParser;
$solver = new LanguageSolver(RegexParser::create(['pcre_version' => '10.42']), new InMemoryDfaCache());
InMemoryDfaCache keeps 1000 automata and drops the older half when full, as the library’s other caches do, and
clearCaches() empties it with them. It also holds 150,000 transitions in all at most, some tens of MB: the oldest
automata go first, and one larger than that alone is not kept. Any DfaCacheInterface (a PSR-backed one, say) can take its place.
A pattern outside the regular subset (backreferences, recursion, …) throws a ComplexityException
instead of returning an answer that would be wrong. The next section lists every reason.
The public classes of PHPRegex\Automata are LanguageSolver, Options\SolverOptions, Options\MatchMode,
Determinization\DeterminizationAlgorithm, Minimization\MinimizationAlgorithm, the four result classes in
Solver\, Model\Dfa and the Model\DfaState it hands out, Solver\DfaCacheInterface, Solver\InMemoryDfaCache, TrivialMatchClassifier with the TrivialMatch and TrivialMatchKind it returns, and Language. Every other class of the namespace is
@internal and may change in any release.
TrivialMatchClassifier::matchedLiteral() is a question built on equivalent() in full-match
mode: the one non-empty string a pattern matches, proven, or null. A pattern made of
literals, groups, one-member classes and fixed repetitions names its candidate, and the
solver checks the pattern against that string quoted byte by byte; a ComplexityException
on the way answers null. See Prefilters.
use PHPRegex\Automata\TrivialMatchClassifier;
(new TrivialMatchClassifier())->matchedLiteral('/(?:foo)/'); // 'foo'
(new TrivialMatchClassifier())->matchedLiteral('/fo?/'); // null
The Language of a Pattern
language() hands out what the automaton of a pattern knows once built, under the match
mode of the options: whether its language is finite, how many strings of each length it
holds, each of them in order, and the strings it rejects.
$solver = new LanguageSolver();
$plates = $solver->language('/^[A-Z]{2}\d{4}$/');
$plates->isFinite(); // true
$plates->size(); // "6760000"
$plates->minLength(); // 6
$solver->language('/^[a-z]+$/')->countOfLength(20); // "19928148895209409152340197376"
iterator_to_array($solver->language('/^[ab]{2}$/')->strings(), false); // ['aa', 'ab', 'ba', 'bb']
Counts are exact decimal strings, however large, with no extension needed. strings() and
nonMembers() are generators: shortest first, then in code point order; they end when
the strings run out, nonMembers() at once for /[\s\S]*/, and an infinite set never
does, so take what you need. The search for the next string is bounded: past a million
steps, or 50,000 remembered states for one length, the generator throws a
ComplexityException. /^(?:b|a{400})$/ hands out b, then throws rather than walk
every length up to 400. Each string nonMembers() hands out is
proven outside the language by the automaton: test fixtures with positives and negatives
both certain. Under the default full match mode a string belongs when the whole of it
matches; ask for MatchMode::Partial to read the subjects preg_match() accepts, a final
newline after $ included.
Lookarounds
Lookarounds keep a language regular, and the solver reads them: a password rule
^(?=.*\d)(?=.*[a-z]).{8,}$ is a language like any other.
$solver = new LanguageSolver();
$solver->subsetOf('/^(?=.*\d)(?=.*[a-z]).{8,}$/', '/^.{8,}$/')->isSubset; // true
$solver->equivalent('/^a(?!b)./', '/^a[^b\n]/')->isEquivalent; // true
$solver->equivalent('/a(?=b)c/', '/[^\s\S]/')->isEquivalent; // true: never matches
A lookahead is a promise about what follows: crossing it starts a run of its body’s automaton on the characters still to come, kept once that run accepts — broken, for a negative lookahead. A lookbehind asks about what came before: the automaton of “anything, then its body” runs from the start of the subject, and the lookbehind reads where it stands. The product of the pattern’s automaton with the pending promises and those runs is an automaton of its own, determinized as any other (Berglund, van der Merwe and van Litsenborgh, “Regular Expressions with Lookahead”, 2021).
A word boundary is two lookarounds in disguise, and reads as them: \b holds between a
word character and something else, (?<=\w)(?!\w)|(?<!\w)(?=\w), \B where it does not.
Word characters are the engine’s: é is one under /u, two bytes that are not without it.
Anchors away from the edges of the pattern read the same way. \A holds with nothing
before, (?<![\s\S]); \z with nothing after, (?![\s\S]); $ and \Z before at
most a newline that ends the subject. Under /m, ^ holds at the start or after a newline
that more follows, and $ before any newline or at the end. So /a\Ab/ matches nothing,
/(?:^|,)a/ finds an a at the start or after a comma, and /^\d+$/m checks one line
among many. Anchors at the edges, \A leading every alternative of a search or \z
closing it, still cost nothing.
A lookaround inside a lookaround, an anchor or word boundary inside one, and the non-atomic
(*napla:...) are refused. The product can grow large; the usual NFA and DFA budgets bound it,
and the work budget counts its moves.
What the Solver Refuses
One taxonomy, one exception (ComplexityException), one message per reason.
The messages below are the texts the library prints; getMessage() returns them
verbatim:
| the pattern holds … | the message begins … |
|---|---|
a backreference, subroutine call, callout or control verb (and \X) |
Backreferences, subroutines, callouts and control verbs carry match state the automata solver cannot read as a pure language. |
| a conditional group | Conditional groups branch on match state the automata solver cannot read as a pure language. |
| a lookaround inside a lookaround | A lookaround inside a lookaround is beyond what the automata solver reads. |
| an anchor inside a lookaround | An anchor inside a lookaround is beyond what the automata solver reads. |
a non-atomic lookaround, (*napla:...) |
A non-atomic lookaround, (*napla:...) or its kind, backtracks into its body, which the automata solver does not read. |
an atomic group (and \R) the solver cannot prove inert |
Atomic groups commit to their first match and never retry, which is ordered behaviour the solver cannot read as a pure language. |
\K or \G |
\K and \G read where a match starts or stood before, which the automata solver cannot read as a pure language. |
| a possessive quantifier the solver cannot prove inert | Possessive quantifiers never give back what they matched, which is ordered behaviour the solver cannot read as a pure language. |
an anchor, an assertion or a lookaround in a group repeated no time, (?:x|(?=a)){0} |
An anchor, an assertion or a lookaround in a group repeated no time still moves where PCRE2 tries a match, which the automata solver does not read. |
a surrogate code point the pattern names under /u |
PCRE refuses any pattern that names a surrogate code point, which the automata solver cannot read as a pure language. |
a newline convention other than \n, such as (*CR), with $, \Z, /m or (?m) |
A newline convention other than "\n" moves where "$", "\Z" and the multiline anchors stand, which the automata solver does not read. |
(*NOTEMPTY) or (*NOTEMPTY_ATSTART), which PHP’s JIT ignores |
(*NOTEMPTY) and (*NOTEMPTY_ATSTART) refuse an empty match without the JIT and are ignored with it, which the automata solver does not read. |
the flag A |
Unsupported regex flags for automata: A. (the pattern’s own flags, in order) |
Two refinements inside those rules:
- Anchors.
^,$,\A,\zand\Zare read wherever they stand, under/mtoo; see Lookarounds. Inside a lookaround they stay refused, with the message above. -
Possessive quantifiers and atomic groups are refused — except when nothing that follows can take the characters back.
/^a*+a$/matches nothing at all, an ordered fact no pure language can say, so it is refused; buta++beforec?dholds, because everything after it starts with characters its atom cannot match. The rule reads the first characters of everything that follows — the rest of the sequence, through followers that may be skipped, and past the sequence’s own end through what follows the capture, the alternation branch or the repetition body it sits in, the loop’s own first characters included — case- and flag-aware, so Symfony’s[^/]++route requirements keep being analyzed. A flat chain of possessives (/x*+ab*+/) is refused: the second possessive sits beyond the next part, which is exactly what the rule cannot see across. So is a possessive whose atom may match one iteration more than one way, as(?:ab?)++,(?:a{2,3})++or(?:a(?:bc|b))++: it gives back nothing inside an iteration either, where the greedy spelling would give abback to a followerb. The atom is a class, a literal, a sequence of them, or an unbounded greedy run of one class ((?:a+)++); a lazy run stops at its first character, and(?:a+?){2}+is refused.An atomic group reads as its body when there is nothing it would keep that a follower needs back: a body that matches one fixed way (
(?>ab)), a greedy run the rule above proves (/^(?>\d+)-x$/), or fixed branches of which none tried first may match the start of a later one, and a later one that may match the start of an earlier one stops where nothing that follows starts:/(?>ab|a)c/holds,/(?>a|ab)c/is refused.\Ris the atomic group(?>\r\n|\v)to PCRE under the default(*BSR_UNICODE), and(?>\r\n|[\r\n])under(*BSR_ANYCRLF): either way it holds unless a\nmay follow it.A lookbehind branch that matches more than one length, as
\Rdoes, compiles from PCRE2 10.43 on when its length is bounded, up to a limit PCRE2 sets when it is built, 255 characters by default: there,/(?<=a{1,255})x/compiles,/(?<=a{1,256})x/and/(?<=a+)x/do not. Before 10.43,/(?<=\R)/is a compile error, where/(?<=a|bc)x/, each branch of one length, compiles. Its body must end where the lookbehind stands, and PCRE2’s interpreter lets a commitment run past that place and fail there, where its JIT reads the subject as ending at it:/(?<=\R)/does not hold between\rand\nunderpcre.jit=0. A commitment a lookbehind ends with is read as if any character followed it, so(?<=\R)and(?<=a{1,2}+)are refused and(?<=\Rx)holds.
An atom the engine itself refuses to define (the character-set query PCRE
rejects) is a refusal too, under the first message — never an approximation:
this solver answers languages, it does not read anything “as any character”.
Naming a surrogate code point under /u — a literal \x{D800}, a class
member, or the endpoint of a range — is the same kind of refusal with its own
message: PCRE refuses to compile the pattern at all, so there is no language
to read. A range that straddles the block with both endpoints outside it
([\x{D7FF}-\x{E000}]) is legal, and its set keeps the two real ends with
the hole out.
On the command line the same refusal is summarized as
Comparison not supported: Pattern contains advanced features (e.g., backreferences).
and the command exits with code 1.
How it Works (Under the Hood)
PHPRegex follows a formal pipeline:
- The pattern’s normalized form (HIR) — where every character set is already the engine’s — becomes an NFA (Thompson construction)
- The product of the two automata is searched breadth first for a string
both take (
intersection()), or the left one takes and the right one does not (subsetOf(), and each side ofequivalent())
The breadth-first search guarantees the shortest possible counter-example when one exists, and of those the least.
Search Strategies
intersection(), subsetOf() and equivalent() search one of two products:
- lazy (default): the product of the NFAs, built as it is reached. An
intersection pairs the states of both NFAs and determinizes neither; an
inclusion pairs the left NFA with the right one determinized one reached
state at a time. The search stops at the depth of the shortest witness:
/a|(?:b{11})+/meets/a|(?:b{13})+/ata, without the 143 pairs the twobloops lead to. - eager: both patterns are determinized and minimized, and the product of the two DFAs is searched.
Neither wins everywhere. /(a|b)*a(a|b){15}/ meets /b+/ in a handful of
pairs, where its DFA passes the 10,000-state limit; 2,000 branches a|a|…
start four million pairs of NFA states, where their DFA holds three states.
The lazy search keeps its pairs under maxDfaStates, each counted as it is
reached, and charges each move to maxTransitionsProcessed; past either
limit it gives up and leaves the answer to the eager search, which reads the
patterns under its own limits: the answer is the eager one’s, and so is a
refusal. With a DFA cache, whose compiled DFAs it reuses, or for a pattern
read as UTF-8 beside one read as bytes, the search is the eager one.
use PHPRegex\Automata\Options\SolverOptions;
use PHPRegex\Automata\Options\SolverStrategy;
$options = new SolverOptions(strategy: SolverStrategy::Eager);
Determinization Strategies
PHPRegex determinizes NFAs using a selectable strategy:
- subset: classic powerset construction.
- subset-indexed (default): pre-indexes the moves by classes of the alphabet, the ranges that every set of the automaton holds alike, and reads each class once for each state rather than each range.
The indexed strategy typically runs faster at the cost of a slightly higher memory footprint.
Selecting a Strategy
CLI:
vendor/bin/regex compare '/foo/' '/bar/' --determinizer=subset-indexed
Symfony bundle:
# config/packages/php_regex.yaml
php_regex:
automata:
determinization_algorithm: subset-indexed
You can also set it programmatically:
use PHPRegex\Automata\Determinization\DeterminizationAlgorithm;
use PHPRegex\Automata\Options\SolverOptions;
$options = new SolverOptions(
determinizationAlgorithm: DeterminizationAlgorithm::SubsetIndexed,
);
Minimization Strategies and Complexity
PHPRegex minimizes DFAs before comparison to shrink the product graph and keep searches fast.
- Hopcroft worklist (default):
O(|Σ_eff| · n log n) - Moore partition refinement:
O(|Σ_eff| · n^2)
Effective alphabet (Σ_eff) means only the symbols that actually appear as DFA transitions are iterated.
This avoids scanning a full Unicode range and keeps minimization proportional to real symbols. For byte-mode
DFAs, Σ_eff is at most 256 symbols and often much smaller; under /u it counts the code-point ranges the
patterns actually use, not the whole U+0000-U+10FFFF span.
Selecting a Strategy
CLI:
vendor/bin/regex compare '/foo/' '/bar/' --minimizer=moore
Symfony bundle:
# config/packages/php_regex.yaml
php_regex:
automata:
minimization_algorithm: hopcroft
You can also override it per command:
bin/console regex:compare '/foo/' '/bar/' --minimizer=moore
Performance
Asking the engine for a character set costs one scan per distinct atom, and the
answers are cached per process: the same \w under /u is asked once, whatever
the number of patterns. Measured over the project’s corpus of about 1,700
real-world patterns:
- 715 distinct atoms scanned once per process, 1.77 s one-time — about 18 % of a cold corpus-wide comparison pass;
- after that one-time cost, the migrated solver runs at parity cold (0.91x the pre-migration time) and faster warm (0.80x), while answering 56 corpus patterns the old conversion refused.
On the Optimizer side, the solver that verifies rewrites keeps a DFA cache, so
a repeated optimize() of the same pattern answers from the cache instead of
rebuilding both automata — measured at roughly two orders of magnitude on the
second run of the corpus’ equivalence questions; a single pass is unchanged.
Safety Limits & Work Budget
Large patterns can cause determinization or minimization to grow quickly, and
matchEquivalent() steps one thread per branch of a wide alternation at every
character. You can enforce a hard work budget using
SolverOptions::maxTransitionsProcessed: it counts the transitions of the
determinization and the minimization, the pairs of states a comparison of two
automata visits, one unit per range of the alphabet for each pair, and the
threads the match solver steps.
The determinization counts each transition it writes, one per range of the
alphabet for every state: a Unicode class such as \pL splits the alphabet
into hundreds of ranges, so a pattern with a few hundred states reaches the
budget, and the memory its table would take stays bounded. The moves are read
once for each class of those ranges, and the minimization splits its groups on
one range of each: four lookaheads of Unicode classes before .{16,}, some two
hundred states over two thousand ranges, fit the default budget. Before it steps a
thread, the match solver also counts the ranges of the classes it splits its
alphabet with, and each class it tests every range against: a literal of a
thousand distinct characters under u reaches the default budget there, in
milliseconds, and its phase is match exploration. Each step then counts,
for every symbol of that alphabet, one unit and one more for each class of the
active threads it tests the symbol against. Its automaton stops at
maxNfaStates, counted at every state it adds, one per character of a
literal included.
use PHPRegex\Automata\LanguageSolver;
use PHPRegex\Automata\Options\SolverOptions;
use PHPRegex\Automata\Exception\ComplexityException;
$solver = new LanguageSolver();
$options = new SolverOptions(maxTransitionsProcessed: 200000);
try {
$solver->subsetOf('/[a-z]+/', '/[a-z0-9]+/', $options);
} catch (ComplexityException $exception) {
$diagnostic = $exception->getDiagnostic();
// ['phase' => 'determinize'|'minimize'|'comparison'|'lookaround bodies'|'lookaround product'|'match exploration', 'states' => ..., 'transitions' => ..., 'alphabet' => ..., 'consumed' => ..., 'limit' => ...]
}
When the budget is exceeded, a ComplexityException is thrown with a diagnostic payload:
phase:determinize,minimize,comparison,lookaround bodies,lookaround productormatch explorationstates: number of DFA states seen so far; incomparison, the pairs of states visited; inlookaround product, the states of the product built so far; inmatch exploration, the states of the two match automata togethertransitions: NFA/DFA transition count at the time of failurealphabet: effective alphabet size; inlookaround product, the classes the alphabet is split into, 0 until it isconsumed: work units consumedlimit: configured budget
A state cap reached (maxNfaStates, maxDfaStates, the match solver’s
configurations) carries a phase and the limit too. A construct the
automata do not read (a backreference, a lookaround the solver refuses)
carries no limit: the diagnostic tells “too costly to answer” from “outside
what the solver reads”.
The bodies of a pattern’s lookarounds are compiled to automata of their own,
and they share one allowance between them rather than one each: a single
budget of maxTransitionsProcessed counts, for all of them together, every
body built, its NFA states, the work of its determinization and minimization,
and the transitions its DFA keeps; the NFA and DFA states of all bodies count
against maxNfaStates and maxDfaStates together. A budget that answers
/(?=a{10})/ and /(?=b{10})/ one at a time can refuse
/(?=a{10})(?=b{10})/, and the diagnostic then names the lookaround bodies
phase. A lookaround repeated by a quantifier, (?:(?=a{99})){100}, is one
body compiled once, not a hundred.
The product of the pattern’s automaton with those bodies then has a budget of
maxTransitionsProcessed of its own, and its diagnostic names the
lookaround product phase. It first splits the alphabet into classes, the
characters that belong to the same sets of the pattern and of the bodies: one
unit for each stretch of the alphabet a set covers, and one for each stretch
kept. Then every move is one unit: a step that reads nothing, or a transition
read on one class, whether it leads to a state or breaks a promise. A Unicode
class cuts the alphabet into hundreds of stretches but only two classes, so
the product reads each state on a few classes: twelve lookaheads of Unicode
classes, /^(?=.*\p{Lu})(?=.*\p{Ll})(?=.*\p{N})...{12,}$/u, reach
maxNfaStates after some 34,000 units of the product, fewer than the 82,000
their twelve bodies count.
Use this to surface safe failure messages in CI or tooling.
Limitations
- Supports the regular subset of PCRE only — no backreferences, no recursion, no atomic or possessive construct the follower rule cannot prove inert. Every refusal names its reason; see What the Solver Refuses.
- The pattern flags
i,s,u,D,mandrare read;x,U,n,J,SandXchange nothing a language says.Ais refused, and so is a newline convention other than\nwhere$,\Z,/mor(?m)would read it, and so are(*NOTEMPTY)and(*NOTEMPTY_ATSTART). - In partial match mode, a search,
$and\Zalso match before a newline that ends the subject, as PCRE’s do without/D:/^ab$/matches"ab\n",/^ab\z/does not. A full match covers the whole subject, so there$is the end of the subject. Inline flags ((?i:...)) are applied where they hold, inlinerand the ASCII options ((?aD),(?aW), …) included;(?^)clearsrand keeps the ASCII options, as PCRE does. - Case-insensitive matching folds single code points, as the engine folds
them. A fold that produces several code points (the Turkish
İ, theDŽdigraph) is outside the model: under/iu,kstill matches the Kelvin sign U+212A andsthe long s U+017F, while the dotlessıstays apart. - Under
/uthe sets cover the code points minus the surrogatesU+D800-U+DFFF; without/uthe alphabet is the 256 bytes, and a multi-byte subject is read byte by byte, as the engine does without/u. - Partial matching is modeled as Σ* L Σ*; an anchor reads where it stands.