php-regex
Health Gecti
- License — License: MIT
- Description — Repository has a description
- Active repo — Last push 0 days ago
- Community trust — 29 GitHub stars
Code Gecti
- Code scan — Scanned 12 files during light audit, no dangerous patterns found
Permissions Gecti
- Permissions — No dangerous permissions requested
Bu listing icin henuz AI raporu yok.
Static analysis, linter & logic solver for PHP regular expressions
PHPRegex: Static Analysis, Linter & Logic Solver
PHPRegex is a PHP 8.1+ library that treats regular expressions as code.
Unlike simple wrappers around preg_match, PHPRegex reads a pattern the way a compiler reads source code: a lexer splits it into tokens, a parser builds them into a tree (the AST), and every analysis runs on that tree. To answer questions such as "do these two patterns match the same strings?", a logic solver also turns the tree into state machines (an NFA, then a DFA) and compares them.
This architecture allows for advanced static analysis:
- Linting: Detect redundancy, useless flags, and common mistakes.
- Safety: Prove a pattern safe from catastrophic backtracking (ReDoS), or hand you the input that triggers it.
- Logic: Tell whether two patterns match the same strings, overlap, or one contains the other (equivalence, intersection, subset), for patterns without backreferences or recursion.
Built for robust regex tooling in PHP projects.
Try it before installing anything: the playground on php-regex.com runs the real PHP and PCRE2 in your browser, in the PHP version you pick, with PHPRegex explaining, linting and dissecting the pattern as you type.
It also runs the five preg_* functions with their flags, draws the pattern as a railroad diagram (Mermaid source, SVG and PNG), compares two patterns, and takes the pattern of a PHP call you paste into it.
The documentation lives at php-regex.com: a
regex tutorial, a guide for every
integration, and the reference pages behind each verdict the library prints.
How to read the verdicts. Every ReDoS verdict carries a label.
(proven)means the analysis checked a model of how PCRE retries the
pattern, one match attempt at a time;(heuristic)means the pattern uses a
feature that model does not cover (a backreference, for example), so
conservative structural rules decided instead. The parser follows
PCRE closely (see the conformance page)
without covering every edge of the engine. Treat findings as leads to
investigate, not as a guarantee; the correctness contracts
spell out what each label promises.
2.0 is coming
The focused php-regex/* packages are published as 2.x-dev, and the stable
2.0 tag is close. Install the package for the surface you need and shape the
release with us:
composer config minimum-stability dev
composer config prefer-stable true
composer require --dev php-regex/regex-cli:2.x-dev
Try it, break it, and tell us what your project needs — feedback and wishes go
to the discussions.
Getting started
If you are new to regex, start with the Regex Tutorial. If you want a short overview, see the Quick Start Guide.
# Install the CLI (the API toolkit comes with it)
composer config minimum-stability dev
composer config prefer-stable true
composer require --dev php-regex/regex-cli:2.x-dev
# Try the command-line tool
vendor/bin/regex explain '/\d{4}-\d{2}-\d{2}/'
The CLI requires the mbstring and tokenizer extensions; the standalone
parser package needs only mbstring.
Every package runs on PHP 8.1 or later, the integrations included: the
Symfony bundle on Symfony 6.4, 7.4 and 8, the Laravel integration on Laravel
10.37 to 13, and on Linux, macOS and Windows alike; the lint's parallel
workers need a PHP that forks, which Windows does not have, and run as one
process there.
PHPRegex is a family of packages, developed together in
php-regex/php-regex and released
with one version number. Install the one you need; the
package guide helps you choose:
| package | what it holds |
|---|---|
php-regex/regex-toolkit |
the Regex facade, a convenience layer over the parser, explain, generator, linter, optimizer, ReDoS and transpiler packages |
php-regex/regex-parser |
lexer, parser, immutable AST, validator, PCRE2 release targeting, AST cache |
php-regex/regex-explain |
explanations, highlighting, ASCII tree, Mermaid and railroad diagrams |
php-regex/regex-optimizer |
shorter equivalent patterns, modernized syntax |
php-regex/regex-generator |
sample strings and test cases |
php-regex/regex-automata |
language equivalence, intersection and subset |
php-regex/regex-redos |
catastrophic backtracking (ReDoS) analysis |
php-regex/regex-transpiler |
JavaScript, HTML pattern and Python targets |
php-regex/regex-linter |
lint rules and pattern extraction from PHP sources |
php-regex/regex-cli |
the regex command |
php-regex/regex-language-server |
diagnostics in any LSP editor |
php-regex/regex-mcp |
the MCP server: regex judgement for a coding agent |
php-regex/regex-phpstan |
the PHPStan extension |
php-regex/regex-phpunit |
match, compilation and proven-linearity assertions for your test suite |
php-regex/regex-infection |
Infection mutators for regex literals, each mutant with the subject that kills it |
php-regex/regex-psalm |
the Psalm plugin: $matches typed from the pattern, invalid patterns reported |
php-regex/regex-rector |
Rector rules: preg_* calls to the string functions they prove equal to |
php-regex/regex-symfony |
the Symfony bundle |
php-regex/regex-laravel |
the Laravel integration |
Coming from 1.x (yoeunes/regex-parser)? See UPGRADE-2.0.md.
What PHPRegex provides
- Deep Parsing: Parse
/pattern/flagsinto a structured, typed AST. - Logic Solver: Compare two regexes using NFA/DFA transformation (intersection, equivalence, subset) with
LanguageSolverfromphp-regex/regex-automata:(new LanguageSolver())->equivalent('/a+/', '/aa*/')->isEquivalentistrue. It works for patterns without backreferences, recursion and the other features listed in the regular subset, and refuses any other pattern with the reason named. Character classes are resolved by asking the PCRE2 release your PHP runs. - ReDoS Analysis: Prove the backtracking cost of a pattern — linear, polynomial or exponential — with the attack input when it is vulnerable, and replay that attack on the running PCRE. Outside the modelled subset, structural heuristics decide and say so.
- Linter: Detect useless flags, redundant groups, and common mistakes via the CLI.
- Explanation: Explain patterns in plain English.
- Formatter: Lay a long pattern out over lines under
x, or compact it to one line, and prove the result matches exactly what the input matched. - Visitor API: A flexible API for building custom regex tooling.
Philosophy & Accuracy
PHPRegex separates what it can guarantee from what is heuristic:
- Guaranteed: parsing and AST structure for the targeted PHP/PCRE version.
- Measured: syntax validation and error offsets follow PHP's engine; the PCRE2 conformance page publishes how closely, case by case.
- Proven: a ReDoS verdict marked
(proven)holds for one match attempt on a model of PCRE's backtracking;safe (proven)means no input can make that attempt take more than a number of steps proportional to the input's length (a linear number): matching time grows with the text, never faster. The ReDoS guide lists its limits. - Heuristic: patterns outside that model (backreferences, conditionals, recursion, …) are judged by structural rules, marked
(heuristic); treat those as potential risk unless confirmed. - Context matters: PCRE version, JIT, and backtrack/recursion limits change practical impact.
Tested against the real engine
Round-trip correctness (compile(parse(x)) behaves like the original) is
verified in CI by differential tests that compare PHPRegex's output against
PHP's native preg_match():
- A fixture of 212 PCRE patterns is checked for validity, match result,
and captured groups (OfficialPcreComplianceTest). - Additional behavioral tests cover named groups, lookarounds, conditionals,
atomic groups, and other features (BehavioralComplianceTest,AdvancedFeaturesComplianceTest). - PCRE2's own official test suite (10.49, pinned) is replayed at compile level
under PHP's compile options: the compile verdict agrees on more than 4,100
of the roughly 4,400 extractable cases, and fewer than 100 patterns that PHP
refuses to compile are accepted. The exact counts, the skipped cases and the
fix plan are on the PCRE2 conformance page.
These tests compare against a limited set of subjects, so they catch clear
regressions but are not a formal proof of full PCRE equivalence. There may
be edge cases that the test suite does not yet cover.
Separately, the linter and ReDoS analyzer have been run over a corpus of
over 1,700 unique patterns collected from around 200 real-world PHP
projects (Symfony,
Laravel, Composer, PHPUnit, …).
This corpus run is not part of the automated CI differential test — it is
a snapshot used to validate that the lint and ReDoS rules produce sensible
output on real code. What it reports on each project is published on the
findings pages; how the corpus is pinned,
rebuilt and swept is on the maintainers page.
How to report a vulnerability responsibly
If you believe a pattern is exploitable:
- Run confirmed mode: it replays the attack on your PCRE and prints the input length that makes
preg_match()fail. - Include the pattern, input lengths, timings, JIT setting, and PCRE limits.
- Verify impact in the real code path before filing a security issue.
See SECURITY.md for reporting channels.
Safer rewrites (verify behavior)
These techniques reduce backtracking but can change matching behavior. Always validate with tests.
/(a+)+$/ -> /a+$/ (semantics often preserved, but verify captures)
/(a+)+$/ -> /a++$/ (possessive, no backtracking)
/(a|aa)+/ -> /a+/ (only if alternation is redundant)
/(a|aa)+/ -> /(?>a|aa)+/ (atomic, avoids backtracking)
How it works
Regex::parse()splits the literal into pattern and flags.- The lexer produces a token stream.
- The parser builds an AST (
RegexNode). - Visitors walk the AST to validate, explain, analyze, or transform.
For the full architecture, see the architecture overview.
CLI quick tour
# Parse and validate a pattern
vendor/bin/regex parse '/^hello world$/'
# Get plain English explanation
vendor/bin/regex explain '/\d{4}-\d{2}-\d{2}/'
# Check for ReDoS: a proven verdict, and the attack when vulnerable
vendor/bin/regex analyze '/(a+)+$/'
# Colorize pattern for better readability
vendor/bin/regex highlight '/\d+/'
# Lay a long pattern out over lines, or back on one with --compact
vendor/bin/regex format '/^(?<user>[\w.+-]+)@(?<domain>(?:[a-z0-9-]+\.)+[a-z]{2,})$/i' --width=40
# Lint your entire codebase
vendor/bin/regex lint src/

PHP API at a glance
use PHPRegex\Toolkit\Regex;
use PHPRegex\Redos\RedosMode;
use PHPRegex\Redos\RedosOptions;
$regex = Regex::create([
'runtime_pcre_validation' => true,
]);
// Parse a pattern into AST
$ast = $regex->parse('/^hello world$/i');
// Validate pattern syntax and semantics
$result = $regex->validate('/(?<=test)foo/');
if (!$result->isValid) {
echo $result->error;
}
// Check for ReDoS (theoretical by default)
$analysis = $regex->redos('/(a+)+$/');
echo $analysis->severity->value; // 'critical'
echo $analysis->headline(); // 'Exponential backtracking (proven)'
echo $analysis->witness->render(); // '"a" x n . "!"': the input that triggers it
// Optional: replay the attack on the running PCRE
$confirmed = $regex->redos('/(a+)+$/', new RedosOptions(RedosMode::Confirmed));
echo $confirmed->isConfirmed() ? 'confirmed' : 'theoretical'; // 'confirmed'
// Get human-readable explanation
echo $regex->explain('/\d{4}-\d{2}-\d{2}/');
// Lay a long pattern out over lines under x, or compact it back to one
$laidOut = $regex->format('/^(?<user>[\w.+-]+)@(?<domain>(?:[a-z0-9-]+\.)+[a-z]{2,})$/i', 40)->pattern;
echo $regex->compact($laidOut)->pattern; // the one-line pattern again
Integrations
PHPRegex integrates with common PHP tooling:
- Symfony bundle: the Symfony guide
- Laravel: the Laravel guide
- Language server: the language server guide
- PHPStan: enabled by extension-installer, or through
vendor/php-regex/regex-phpstan/extension.neon. It reports a pattern your
target PHP refuses while the PHP running PHPStan compiles it; lint rules and
ReDoS analysis come withrules.neon. See the PHPStan guide - Psalm:
vendor/bin/psalm-plugin enable php-regex/regex-psalmtypes$matchesfrom the pattern wherepreg_match()returned 1 and afterpreg_match_all(), and reports the patterns your target PHP refuses asInvalidRegexPattern. See the Psalm guide - Rector:
RegexSetList::STRING_FUNCTIONSrewritespreg_match('/^https:/', $url)
into\str_starts_with($url, 'https:'),preg_replace()intostr_replace()andpreg_split()intoexplode(), only where the automata prove them equal.
See the Rector guide - GitHub Actions:
uses: php-regex/[email protected]runs the lint from the
release PHAR, its findings annotated on the pull request.
See the CLI guide - Demo applications: complete Symfony and Laravel apps under
demo/,
wired to this repository through a Composer path repository and run in CI;
standalone scripts cover every library surface in the same folder
Performance
PHPRegex measures its own time and memory with PHPBench, one group per subsystem (lexer, parser, validate, lint, redos, redos-corpus, automata, optimizer, capture-shape, formatter).
- Run one group:
composer bench -- --group=automata - Run the whole suite:
composer bench(long;redos-corpus, one variant per corpus pattern, is the longest group)
See the maintainers guide for the inputs and how to add a case.
CI also counts the instructions, cycles and memory of the hot paths and of the inputs once read in quadratic time with Tally, which repeat from run to run, and fails a pull request past its expected numbers or its complexity class: task tally counts them locally, with Docker (see counted benchmarks).
Documentation
Read the docs online at https://php-regex.com.
Start here:
Guides:
Key references:
- Architecture
- Concepts: AST, PCRE versions, how PCRE2 matches, ReDoS, visitors
- API Reference
- Diagnostics
- Feature Support Matrix
- PCRE2 Conformance
- FAQ & Glossary
- Backward Compatibility Promise
Contributing
Contributions are welcome! See CONTRIBUTING.md to get started.
# Set up development environment
composer install
# Run tests
composer phpunit
# Check code style
composer phpcs
# Run static analysis
composer phpstan
Sponsors
If PHPRegex saves you time, consider sponsoring its maintenance,
for the amount you choose: developers see their name on every documentation page, companies their logo.
Like a Symfony component, each part of PHPRegex — the core engine, the linter and ReDoS analysis, the
tutorial, each integration — can be backed by one company for a whole release, named on its pages and in
the README of its packages. See how sponsorship works; the people and
companies who already sponsor are listed in BACKERS.md.
Support
If you run into issues or have questions, please open an issue on GitHub: https://github.com/php-regex/php-regex/issues.
License
Released under the MIT License.
Yorumlar (0)
Yorum birakmak icin giris yap.
Yorum birakSonuc bulunamadi