php-regex / regex-transpiler
Transpiles PCRE patterns to JavaScript and Python regular expressions, with the losses reported.
Fund package maintenance!
Requires
- php: >=8.1
- ext-mbstring: *
- php-regex/regex-parser: 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:47 UTC
README
PHPRegex Transpiler
Transpiles PCRE patterns to JavaScript regular expressions, HTML pattern attributes and Python regular expressions, with the losses reported.
Documentation: php-regex.com — the API reference documents transpile() in full.
Features
- Three dialects, the cases of the
Dialectenum:JavaScript(javascript, aliasjs),HtmlPattern(html_pattern, aliashtml) andPython(python, aliaspy), each producing a paste-ready literal and a constructor call - Dialect rewrites:
(?P<name>)becomes(?<name>)in JavaScript,\k<name>becomes(?P=name)in Python,\hand\vbecome character classes - What a target reads otherwise is written out as PCRE reads it:
$, which also matches before a final newline,^and$underm, the dot, which leaves out\nalone,\swithoutu, six bytes in PHP where JavaScript's also takes the Unicode spaces, and\S, its complement, which takes a byte ofU+00A0in PHP where JavaScript's leaves that space out, and, underu,\d,\w,\sand\b, which PHP reads in Unicode - Flags are mapped per target: JavaScript keeps
i,s,u, gainsuwhen Unicode escapes need it, and has/m,/D,/xand/Uapplied while printing; Python keepsiands, gainsre.ASCIIwithoutu, has/m,/D,/xand/Uapplied while printing, and spells flags inline or asreconstants; every target drops/S, which PHP has ignored since 7.3, with a note - Warnings list every rewrite to review, and the first set that takes a byte in PCRE and a character in the target when the pattern has no
u; notes list the flags applied or dropped - A construct the target cannot express without matching otherwise —
\wunderuin Python, a possessive quantifier or an atomic group in JavaScript, and in Python unlesspythonVersionis 3.11 or later, a backreference to a group that may not have matched in JavaScript — throws aTranspileExceptioncarrying the position in the pattern - Every target is checked against its own engine: the test suite runs the transpiled patterns in Node and Python on the subjects
preg_match()is run on, and compares the matches and the groups
Installation
composer require php-regex/regex-transpiler
PHP 8.1 or newer. php-regex/regex-parser and php-regex/regex-automata are
pulled in automatically.
Configuration
transpile() takes an optional TranspileOptions object:
allowLookbehind(bool, defaulttrue) —falsemakes lookbehind throw for JavaScript targets.pythonVersion(string or null, defaultnull) — the oldest Python the pattern runs on, as'3.11'or'3.11.4'. Python'sretakes atomic groups and possessive quantifiers from 3.11: from that version they are written, before it, or withnull, they are refused.
use PHPRegex\Transpiler\Dialect; use PHPRegex\Transpiler\Transpiler; use PHPRegex\Transpiler\TranspileOptions; $result = (new Transpiler())->transpile('/\d++(?>px|em)/', Dialect::Python, new TranspileOptions(pythonVersion: '3.12')); echo $result->literal; // r'(?a)\d++(?>px|em)'
A possessive quantifier is the atomic group around the greedy repetition to PCRE, and is written so where Python's
own goes wrong: before 3.11.5, where a possessive repetition inside another runs past its end (a++ is (?>a+) for
'3.11'), and over a group, which Python 3.11 to 3.12.7 and 3.13.0 lose the capture of ((a|b)++ is (?>(a|b)+)).
Usage
A PCRE pattern with a named group and a backreference, for a JavaScript codebase:
use PHPRegex\Transpiler\Dialect; use PHPRegex\Transpiler\Transpiler; $transpiler = new Transpiler(); $result = $transpiler->transpile('/(?P<word>\w+)\k{word}/i', Dialect::JavaScript); echo $result->literal, PHP_EOL; // /(?<word>\w+)\k<word>/i // "$" also matches before a newline that ends the subject; JavaScript's does not. echo $transpiler->transpile('/^\d+$/', 'javascript')->literal, PHP_EOL; // /^\d+(?=\n?$)/
The dialect is a Dialect case, or a name Dialect::fromName() takes, as the
examples below write it: javascript or js, html_pattern, html-pattern
or html, python or py, in any case. Dialect::names() lists them all; a name no
dialect answers to throws InvalidRegexOptionException before the pattern is
read. $dialect->label() is the name a console shows it under: JavaScript,
HTML pattern attribute or Python.
Without a parser the transpiler reads with RegexParser::create(); pass the
one your code reads with, as new Transpiler($parser), to read the pattern for
its target and limits.
For Python, the literal is a raw string carrying the flags inline, and the constructor is a re.compile() call.
Without u PCRE reads \w, \d, \s, \b and case in ASCII, so the pattern gains re.ASCII:
$result = $transpiler->transpile('/(?P<word>\w+)\k<word>/i', 'python'); echo $result->literal, PHP_EOL; // r'(?ai)(?P<word>\w+)(?P=word)' echo $result->constructor, PHP_EOL; // re.compile(r'(?P<word>\w+)(?P=word)', re.ASCII | re.IGNORECASE)
Every rewrite is reported, and what a target cannot express is refused rather than approximated:
$result = $transpiler->transpile('/\p{L}+/', 'javascript'); echo $result->literal, PHP_EOL; // /\p{L}+/u echo $result->warnings[0], PHP_EOL; // Added /u for Unicode property escapes. // PCRE2 reads a bare script name as the script's extensions (from 10.40; the script alone before); JavaScript names them. echo $transpiler->transpile('/\p{Han}+/u', 'javascript')->literal, PHP_EOL; // /\p{Script_Extensions=Han}+/u try { $transpiler->transpile('/a++/', 'javascript'); } catch (\PHPRegex\Transpiler\Exception\TranspileException $e) { echo $e->getMessage(), PHP_EOL; // Possessive quantifiers are not supported in JavaScript. }
For an HTML form, the pattern attribute matches the whole value under the
v flag; the html_pattern target pads an unanchored side so the attribute
accepts what preg_match() finds, and escapes in classes what v reserves:
$result = $transpiler->transpile('/^[\w.-]+@[\w-]+\.[a-z]{2,}$/', 'html_pattern'); echo $result->literal, PHP_EOL; // ^[\w\.\-]+@[\w\-]+\.[a-z]{2,}$ echo $transpiler->transpile('/\d{4}/', 'html')->literal, PHP_EOL; // [\s\S]*(?:\d{4})[\s\S]*
No flag reaches the attribute. /i, (?i) and (?i:…) are spelled out:
each letter, class or property is written with every character the running
PCRE takes for it caselessly, so the attribute works in every browser that
has the v flag, and under u the Kelvin sign and the long s come along:
echo $transpiler->transpile('/^[a-z]+-\d+$/i', 'html')->literal, PHP_EOL; // ^[a-zA-Z]+-\d+$ echo $transpiler->transpile('/^ok$/iu', 'html')->literal, PHP_EOL; // ^[oO][kK\u212A]$
A backreference under /i is refused: it would match its group's text in
one case only. /s, /m and /D change nothing in a field value, which
holds no line break. /S, which PHP has ignored since 7.3, is dropped with a
note, there as for JavaScript, and /U or (?U) swaps greedy and lazy in the
quantifiers it governs: /<.+>/U is /<[^\n]+?>/ for JavaScript, the dot
written as PCRE reads it.
JavaScript matches a lookbehind right to left, where PCRE matches it left to
right. A group in a lookbehind branch of more than one length, a group
repeated in a lookbehind, and a reference to a group of the same lookbehind
would be read otherwise, and are refused: on abc, /(?<=(ab|a)b?)c/
captures ab in PCRE and a in JavaScript. A branch of one length with no
group repeated in it is printed as it reads.
JavaScript and Python read characters, where PCRE without u reads bytes. A
multibyte character written whole outside a class (/café/) stays that
character. The rest has no equivalent there and is refused with the advice that
works: a byte above 0x7F on its own, as an escape (\xE9, [\x80-\xFF]) or
as the last byte a quantifier repeats (/é+/), asks for u; a raw byte of
invalid UTF-8 asks to be written as the character, as UTF-8, before u, which
refuses such a pattern; and a multibyte character in a class (/[é]/), each of
whose bytes PCRE reads as a member of its own, asks for u. Before advising
u, the transpiler asks the engine whether the pattern compiles with it: where
something else is refused under u (/[é](?<=\C)/, a \C in a lookbehind),
the advice says to rewrite that construct first. Adding u changes what the
pattern matches, characters instead of bytes (/[é]/ matches à through its
first byte, /[é]/u does not): confirm that matching characters is what the
pattern means before taking the advice.
A set is not refused, where PCRE takes one byte for it and the targets one
character: most patterns hold a dot or a negated class, and on ASCII subjects
the two agree. Once the set reaches past ASCII (the dot, a negated class, \D,
\W, \S, \h, \v, a property) they differ on a subject holding a
character outside it, and the first such set is named in a warning, once per
pattern, with the advice a refusal gives:
$result = $transpiler->transpile('/^\S+$/D', 'javascript'); echo $result->literal, PHP_EOL; // /^[^\t-\r ]+$/ echo $result->warnings[0], PHP_EOL; // Without the u flag "\S" at offset 1 takes one byte in PCRE and one character in this target, so the two differ on a subject holding a character outside ASCII; under u, for UTF-8 subjects, they agree. Add u. var_dump($transpiler->transpile('/^\S+$/Du', 'javascript')->hasWarnings()); // bool(false)
PCRE2 makes a character repeated before an atomic group, or a possessive repeat
of a group, that may match nothing possessive, as if the group could not be
skipped: /a+(?:b)?+a/ finds nothing in aa. JavaScript and Python run the
repeat as written, and find aa with what is written for them, a+(?:b)?a and,
from Python 3.11.5, a+(?:b)?+a. Such a pattern is not refused either, most
subjects leaving the repeat nothing to give back: the first such repeat is named
in a warning, once per pattern, with the group PCRE2 reads it against:
$result = $transpiler->transpile('/a+(?:b)?+a/', 'javascript'); echo $result->literal, PHP_EOL; // /a+(?:b)?a/ echo $result->warnings[0], PHP_EOL; // PCRE2 makes "a+" at offset 0 possessive before "(?:b)?+" at offset 2, as if that group could not be skipped, and this target does not: the two differ on a subject where the repeat must give back to what follows the group. var_dump($transpiler->transpile('/a+x(?:b)?+a/', 'javascript')->hasWarnings()); // bool(false) var_dump($transpiler->transpile('/a+(?:b)?+c/', 'javascript')->hasWarnings()); // bool(false)
PCRE2 reads the repeat against what stands after it, no further than the first
character that must be there, and leaves a lazy repeat as written: neither
/a+x(?:b)?+a/ nor /a+?(?:b)?+a/ is warned of.
Nor is a repeat with nothing to give back: where nothing that may follow it, up
to the end of the pattern or of an atomic group around it, starts with a
character it takes, the two find the same match in every subject.
/a+(?:b)?+c/, /a+(?:b)?+$/ and /a+(?:b)?+/ get no warning;
/a+(?:b)?+A/i and /a+(?:b)?+c?a/ do, and so does a repeat followed by what
is not read that closely: a lookaround, a backreference, an assertion other than
$, \Z and \z.
PCRE2 reads the second alternative of a group repeated no time as the item the
pattern opens with: /(?:x|.*){0}a/ finds nothing in ba, the .* making
every match start at the start of a line, and /(?:x|(?=a)){0}\w/ nothing in
"\tb". JavaScript and Python skip such a group and find a match, so a pattern
where a group repeated no time holds, in an alternative after its first, a
repeat from zero without bound, an anchor, an assertion or a lookahead is
refused, for every dialect, at the offset of that group:
try { $transpiler->transpile('/(?:x|.*){0}a/', 'javascript'); } catch (\PHPRegex\Transpiler\Exception\TranspileException $e) { echo $e->getMessage(); // A group repeated no time that holds, in an alternative after its first, a repeat from zero without bound, an anchor, an assertion or a lookahead cannot be carried into this target: PCRE2 reads that alternative as the item the pattern opens with, "/(?:x|.*){0}a/" finding nothing in "ba", where the target finds "a". } echo $transpiler->transpile('/(?:x|.+){0}a/', 'javascript')->literal; // /(?:x|[^\n]+){0}a/
Documentation
- API reference — the
transpile()entry point and theTranspileResultfields - CLI guide — the
regex transpilecommand, its--dialectoption and its exit codes - Backward compatibility promise — what stays stable across releases
Resources
- Upgrading from 1.x — moving from
yoeunes/regex-parser1.3 to 2.0, every change that needs one on your side - Documentation
- The parsing core it builds on: regex-parser
- 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-transpiler 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.