php-regex / regex-optimizer
Rewrites regex patterns into shorter equivalents and modernizes old syntax; equivalence can be proven, opt-in, by regex-automata.
Fund package maintenance!
Requires
- php: >=8.1
- ext-mbstring: *
- php-regex/regex-automata: v2.0.0-RC1
- php-regex/regex-parser: v2.0.0-RC1
- php-regex/regex-redos: v2.0.0-RC1
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-04 22:23:34 UTC
README
PHPRegex Optimizer
Rewrites regex patterns into shorter equivalents and modernizes old syntax; equivalence can be proven, opt-in, by regex-automata.
Documentation: php-regex.com — the API reference documents optimize(), and the correctness contracts spell out what each rewrite must prove.
Features
[0-9]becomes\d; character class members are sorted, merged and deduplicated- Repeated items collapse into a quantifier,
/aaaa/becoming/a{4}/, frommin_quantifier_countrepetitions on - Alternatives sharing a prefix share it,
/abc|abd/becoming/ab(?:c|d)/— opt-in - A quantifier becomes possessive where nothing after it can take back what it matched,
/[0-9]+;/becoming/\d++;/— opt-in - Each rewrite can be proven by the automata engine to write the same
$matches, or at least to match the same strings, before it is offered — opt-in RedosRepairerrepairs a pattern open to catastrophic backtracking,/href="([^"]+)*"/becoming/href="([^"]*)"/, each repair proven linear and, when the automata can tell, proven to match the same subjects- A
Modernizervisitor cleans legacy syntax: unneeded escapes dropped, redundant non-capturing groups unwrapped,\1written\g{1} - A pattern that cannot be improved comes back unchanged, with an empty change log
Installation
composer require php-regex/regex-optimizer
Requires PHP 8.1+. MIT licensed. php-regex/regex-parser, and the php-regex/regex-automata
engine the equivalence proof runs on, are installed with it. This package is part of
PHPRegex, released with its siblings under one version number.
Configuration
optimize() takes an OptimizerOptions value, or null for the defaults. Its
constructor names each option below in camelCase (verifyWithAutomata for
verify_with_automata); a configuration array keyed in the snake_case names
becomes one through OptimizerOptions::fromArray(), and regex.json and the
PHPStan parameters spell the same options in camelCase
(OptimizerOptions::fromCamelCaseArray()).
| Option | Type | Default | What it does |
|---|---|---|---|
digits |
bool | true |
[0-9] becomes \d |
ranges |
bool | true |
runs of consecutive characters become ranges |
canonicalize_char_classes |
bool | true |
members of a class are sorted and merged, [cbaa] becoming [a-c]; a class whose members would only move keeps its order |
possessive |
bool | false |
a quantifier becomes possessive where nothing after it can take the match back |
factorize |
bool | false |
alternatives sharing a prefix share it |
min_quantifier_count |
int | 4 |
how many repetitions of an item become a quantifier, at least 2 |
verify_with_automata |
bool | true |
a rewrite is only offered when the automata prove it writes the same $matches, or, where the match solver does not read it, when it reads as the pattern does or each part it changed is proven alone |
possessive and factorize are off by default: a backreference can make a
possessive quantifier change what the pattern matches, and factorization makes
an /x pattern harder to read. verify_with_automata is on, as it is for the
lint's suggestions, the PHPStan rule and the editor's quick fix: a rewrite it
disproves, or cannot prove within a budget of its own, is withdrawn, the
original pattern returned. The proof builds automata for both patterns: on some
600 patterns gathered from open-source projects it made optimize() about two
and a half times as slow on average, about a second for the slowest, and
withdrew none of the rewrites. Turned off, the rewrites ship as the rewriter
writes them, but one that adds a possessive quantifier or an atomic group,
which is proven whatever the option says. A pattern where a call runs a repeat
whose count may vary, a+ or a{2,3} but not a{2} nor a repeated call, in
the group it calls or anywhere when the pattern calls itself whole, is not
rewritten at all, whatever the options say, but for a useless s or m:
PCRE2 compiles such a pattern by how all of it is written, and its JIT then
misses matches its interpreter finds. /(?:x){0}(a+b)c(?1)d/ keeps its zero
repeat, as /(a+b)c(?1)d/ finds nothing in abcabcabd with the JIT where
the pattern finds abcabd. A rewrite whose possessive
quantifiers are not proven is made again without them, and the other rewrites
ship: the proof reads no possessive quantifier in a pattern that holds \b
or a reference, and under possessive /\d+y\b/s still becomes /\d+y\b/.
A lookaround is read: /(?=x)xa+b/ becomes /(?=x)xa++b/, /\d+x(?!y)/s
becomes /\d++x(?!y)/ and /(?<=a)[0-9]+x/ becomes /(?<=a)\d++x/. A
repetition right before a lookaround is made possessive where the lookaround
cannot hold once the repetition gave back: /a+(?=b)/ becomes /a++(?=b)/,
the lookahead failing on the a given back, and /a+(?!b)c/ becomes
/a++(?!b)c/, the c failing there. /a+(?!b)/ stays greedy, as it finds
a in aab where /a++(?!b)/ finds nothing, and so does /a+(?=a)/. A
rewrite refused whole still loses the s or the m nothing in the pattern
reads, which moves no bracket and no repeat and needs no proof: /a+(?:b)?+a/m
becomes /a+(?:b)?+a/, the group PCRE2 reads to make a+ possessive kept.
A group a DEFINE holds that no call runs is read as any other:
/(?(DEFINE)(?<n>a+b?))a/ becomes /(?(DEFINE)(?<n>a++b?))a/. A group that
calls itself is read through every call, what may follow it after each
return included, where the rewrite changes a repetition outside it:
/a+b(x(?1)?y)/ becomes /a++b(x(?1)?y)/. The
rewrite reads the flags in force where each item stands: /(?i)a+b?c/ becomes
/(?i)a++b?c/, while /(?i)a+b?A/ stays greedy, and an option setting that
names U keeps every quantifier of the pattern as written. Beside a
non-atomic lookaround, (*napla:...) or (?*...), a repetition is read as
anywhere else, /(*napla:x)xa+b/ becoming /(?*x)xa++b/ and
/(*napla:xa+b)x/ becoming /(?*xa++b)x/. Past the end of a non-atomic
lookahead the engine reads what follows from where the lookahead stands,
whatever its body matched, and fails there again on every way the body ends:
a repetition that may end one is made possessive, /(*napla:xa+)x/ becoming
/(?*xa++)x/, unless the pattern holds a reference, a condition on a group or
a scan substring, which may read what the body captured:
/^(*napla:x(a+b?))x[ab-]*\1$/ matches xaaba, group 1 giving an a back
to the reference, where (a++b?) finds nothing, and stays greedy. So does a
repetition that may end a non-atomic lookbehind, (*naplb:...) or (?<*...).
A repetition that ends its group reads what follows the group, every
call of it and the end of the pattern: /(a+)c/ becomes /(a++)c/, and
/(a+)a/ stays greedy. A repeated group is made possessive only where every
run of its body matches one way, characters and literals in a row, and what
follows never starts as a run does: /(?:ab)+b/ becomes /(?:ab)++b/, while
/(?:b|ba)*c/ stays greedy, as a run of ba may follow one of b, and
/[a-z]+(?:-[a-z]+)*$/ becomes /[a-z]++(?:-[a-z]++)*$/. Under a limit the
pattern sets on what PCRE2 spends on a match, (*LIMIT_MATCH=n),
(*LIMIT_DEPTH=n) or (*LIMIT_HEAP=n), every repeated group stays greedy, as a
possessive one may spend more of it without the JIT:
/(*LIMIT_MATCH=4)c(?:ab)+e/ matches cababe, on which
/(*LIMIT_MATCH=4)c(?:ab)++e/ gives up. A repeated character or class spends
no more, and is still made possessive there. Every repetition inside a group a call runs, a group a DEFINE
holds included, and everywhere in a pattern that calls itself whole, stays
greedy, whatever follows it: PCRE2's JIT, which PHP runs by default, misses
matches of a possessive quantifier there that its interpreter finds.
/(a++)c(?1)d/ finds no match in acacad with the JIT, from PCRE2 10.34 to
10.49, where /(a+)c(?1)d/ matches acad, so /(a+)c(?1)d/,
/(a+b?)c(?1)d/ and /(?&n)c(?(DEFINE)(?<n>a+b?))/ stay as written. A
repetition outside every group a call runs is read as before: /a+;(x)(?1)/
becomes /a++;(x)(?1)/. The rewrite reads the flags in force where each item
stands: /(?i)a+b?c/ becomes /(?i)a++b?c/, while /(?i)a+b?A/ stays
greedy, and an option setting that names U keeps every quantifier of the
pattern as written. A repetition that ends its group
reads what follows the group up to the end of the pattern: /(a+)c/ becomes
/(a++)c/, and /(a+)a/ stays greedy.
A rewrite holds whatever locale the program runs under. Without u, PHP builds
the tables of \w, \s and the POSIX classes from LC_CTYPE once a program
calls setlocale(): under a Latin-1 locale \w takes "\xE9", which
[a-zA-Z0-9_] does not, and with u it takes every letter: a word class
is never written \w.
[0-9] becomes \d under every locale, as the C library's digits are the ten
ASCII ones, but not under u or (*UCP), where \d matches every decimal
digit.
Under /x the rewrite keeps the pattern as its author laid it out: only the
parts it changes are written again, in place, and the newlines, indents and
comments around them stay. The lint suggests for such a pattern what
optimize() gives it with factorize off, whatever its options say, so the
alternatives keep the order and the lines the author gave them.
A rewrite compiles wherever the original does, for the target the parser judges
for: the automata read what a pattern matches, never whether PCRE compiles it,
so a rewrite PCRE would refuse, as (?<=abc|abde) factorized into
(?<=ab(?:c|de)) for PHP 8.2, whose PCRE2 refuses a lookbehind branch of two
lengths, is withdrawn whatever the options say. A DEFINE group keeps its
quantifier as written, and a run of the same item is counted up to 65535, the
largest count PCRE takes.
Read from an array, an unknown key or a value of the wrong type throws InvalidRegexOptionException. The 1.x names
autoPossessify and allowAlternationFactorization were renamed possessive and factorize:
the old names meet the same unknown-option error as any typo.
Usage
use PHPRegex\Optimizer\Optimizer; $optimizer = new Optimizer(); $result = $optimizer->optimize('/[0-9][0-9][0-9][0-9]/'); echo $result->optimized, PHP_EOL; // '/\d{4}/' echo $result->changes[0], PHP_EOL; // 'Wrote [0-9] as \d.' echo $result->kinds[0]->value, PHP_EOL; // 'digits', a RewriteKind var_dump($result->proven); // bool(true): the automata checked the rewrite
Each rewrite is opt-out: turn off the ones you do not want, keep the rest.
use PHPRegex\Optimizer\OptimizerOptions; $result = $optimizer->optimize('/[abc][0-9]/', new OptimizerOptions(digits: false)); echo $result->optimized; // '/[a-c][0-9]/'
The two off-by-default rewrites, turned on:
$options = new OptimizerOptions(possessive: true, factorize: true); echo $optimizer->optimize('/[0-9]+;/', $options)->optimized, PHP_EOL; // '/\d++;/' echo $optimizer->optimize('/abc|abd/', $options)->optimized, PHP_EOL; // '/ab(?:c|d)/'
The instance keeps the solver its automata checks ask: keep one instance for
a batch of patterns rather than building one per call. The check of a
rewrite builds no DFA to keep between calls, so the constructor takes the
parser alone, and that one is optional: without it the optimizer reads with
RegexParser::create(). Pass the parser your code already reads with, as
new Optimizer($parser), to optimize for its target, cache and limits.
To take the rewrite unproven, faster:
$result = $optimizer->optimize('/[0-9][0-9][0-9][0-9]/', new OptimizerOptions(verifyWithAutomata: false)); echo $result->optimized; // '/\d{4}/'
The Modernizer visitor rewrites old syntax on the AST; render its result with
the parser's printer:
use PHPRegex\Optimizer\Modernizer; use PHPRegex\Parser\Printer\PatternPrinter; use PHPRegex\Parser\RegexParser; $parser = RegexParser::create(); $modernized = $parser->parse('/a\-(?:[0-9])/')->accept(new Modernizer()); echo $modernized->accept(PatternPrinter::asWritten()); // '/a-\d/'
[\t\n\x0B\f\r ] becomes \s only when the Modernizer is given a target whose
locale is C or POSIX, new Modernizer($parser->target()): without u, most other
locales give \s the no-break space, byte 0xA0, which the class does not hold. The
release of the target counts as well: before PCRE2 10.44, or without a target, the
Modernizer keeps the shapes the JIT of 10.39 to 10.42 reads otherwise than its
interpreter, such as an atomic group with an empty last branch, /(?>(?:b)*+..+|)b/.
Documentation
- API reference —
optimize()in full: its options, read from a value or a configuration array, andOptimizationResult - Correctness contracts — what the optimizer guarantees, and when it declines a rewrite
- Backward compatibility promise — the public surface of this package and what stays stable within 2.x
- Feature support matrix — which constructs each analyzer, the optimizer included, handles
Resources
- Upgrading from 1.x — moving from
yoeunes/regex-parser1.3 to 2.0, every change that needs one on your side - The batteries-included facade: regex-toolkit
- The equivalence engine: regex-automata
- Documentation
- Changelog
- Report issues and send pull requests in the main PHPRegex repository
Sponsors
This package belongs to the Core engine spot, which one company backs for a whole release. The spot is open
for PHPRegex 2.0: its company is named here — in every vendor/php-regex/regex-optimizer that Composer installs — and on its documentation pages.
The first to ask takes it: see how spots work.
Anyone can back PHPRegex, for the amount they choose. The people and companies who already do are listed in BACKERS.md.
License
MIT. See LICENSE.