Laravel Guide

The service provider registers a Regex service (and the Regex facade) for your application and the php artisan regex:* commands. Package discovery enables it on install.

Requires Laravel 10.37 or later, 11, 12 or 13, and PHP 8.1 or later (8.2 for Laravel 11 and 12, 8.3 for Laravel 13). Laravel 10 and 11 carry a security advisory with no fixed release (PKSA-mdq4-51ck-6kdq), so Composer refuses to install them unless the project’s audit settings in composer.json (config.audit.block-insecure, config.audit.ignore) allow it. The symfony/console requirement takes the same releases as the Symfony integration — 6.4 LTS, 7.4 and 8 — so a Laravel 11 or 12 app holding an earlier Symfony 7.x resolves Console to 7.4 with the package.

Installation

composer config minimum-stability dev
composer config prefer-stable true
composer require php-regex/regex-laravel:2.x-dev

Publishing the configuration is optional: a key missing from your file takes the package default, so publish it only to customize it:

# Optional: publish config/php-regex.php
php artisan vendor:publish --tag=php-regex-config

First Run

Lint the patterns of your application right away; no configuration is needed:

php artisan regex:lint

It reads app/ by default and prints the same report as vendor/bin/regex lint (the CLI guide shows a sample).

From your code, the Regex facade answers in one line:

use PHPRegex\Laravel\Facades\Regex;

Regex::validate('/^[a-z0-9-]{3,}$/')->isValid; // true

Using the service shows what else the facade does, and Commands lists every command.

Configuration

config/php-regex.php, with its defaults. A config/regex-parser.php published by 1.x is no longer read and nothing warns about it: publish the new file, move your settings to it and delete the old one.

return [
    'max_pattern_length' => 100_000,
    'max_lookbehind_length' => 255,
    // Whether the Regex service also compiles every pattern with the running
    // PHP. regex:lint never does.
    'runtime_pcre_validation' => false,
    // The PHP version, PCRE2 release and LC_CTYPE locale regex:lint judges
    // patterns for.
    'php_version' => null,   // "8.2", "8.2.4", 80200, or a constraint like ">=8.1"
    'pcre_version' => null,  // "10.42"
    'locale' => null,        // "tr_TR.UTF-8"; the locale of the PHP running the command
    'cache' => [
        'store' => null,     // a Laravel cache store, used before "directory"
        'directory' => '{storage_path}/framework/cache/php-regex',
        'prefix' => 'regex_',
    ],
    'redos' => [
        'enabled' => false,
        'threshold' => 'high', // low, medium, high or critical, in any case
        'ignored_patterns' => [],
    ],
    'analysis' => [
        'complexity' => false, // regex:lint reports complex patterns
        'warning_threshold' => 50,
    ],
    'automata' => [
        'minimization_algorithm' => 'hopcroft',          // hopcroft or moore
        'determinization_algorithm' => 'subset-indexed', // subset or subset-indexed
    ],
    'optimizations' => [
        'digits' => true,
        'word' => true,
        'ranges' => true,
        'canonicalize_char_classes' => true,
        'possessive' => false,
        'factorize' => false,
        'min_quantifier_count' => 4,
        'verify_with_automata' => true, // suggest only the rewrites the automata prove
    ],
    // The calls regex:lint reads patterns from, as "extraction" of regex.json.
    'extraction' => [
        'interop' => null,   // null: every preset; a list: exactly those; []: no preset
        'functions' => [],   // your helpers: "App\Support\Str::matches#1"
    ],
    'paths' => ['app'],                                // read from base_path()
    'exclude' => ['vendor', 'node_modules', 'storage'], // directories of the application
    'vendor_paths' => null,                             // libraries read for declared patterns, vendor/ by default
    'report_unmatched_ignores' => true, // report the @regex-ignore markers that silence nothing
    'ide' => env('PHP_REGEX_IDE', env('APP_EDITOR', null)),
];

paths and exclude are read from base_path(): regex:lint lints the same files whatever directory it runs from. An exclude names a directory of the application, wherever it lies under the paths, never one above it: Testbench’s skeleton, which lives under vendor/, is linted. It may also be the path of a file or a directory, behind ./ or absolute, and it leaves the validation rules of a file out as it leaves out the file’s patterns. The paths given to regex:lint on the command line are read from the working directory.

A key missing from your file takes the package default, inside each section too: a file published by an older release keeps working after an upgrade.

The automata settings are the defaults of regex:compare; its --minimizer and --determinizer options override them.

extraction takes the presets and the helpers regex lint takes under extraction in regex.json (see the CLI guide); the package does not read regex.json. interop left at null, or missing, reads every preset, those a later release adds included; a list reads exactly the presets it names. Each key falls back to its default alone: setting interop keeps functions at [], and the other way round. A name that is no preset stops regex:lint, exit code 2, as any setting of config/php-regex.php it cannot read, naming the preset it most likely means:

Invalid config/php-regex.php: Unknown extraction preset "laravel-str" in php-regex.extraction.interop: did you mean "illuminate-support"?

An entry of either list that is no string, a false say, is ignored, and regex:lint says so under its banner, or on stderr with --format=json and the other machine formats, the warning naming its type:

Warning: Extraction interop entry ignored: expected a string, got bool.

A functions spec the lint cannot read, x#a or x#1$ say, is ignored with Malformed pattern function "x#a", ignored.

An unknown redos.threshold stops regex:lint with an error naming the value, and leaves every other artisan command working. safe and unknown are not thresholds: they are the verdicts a pattern gets.

redos.ignored_patterns lists patterns, fragments of patterns or whole regexes the risk analysis skips. A fragment, (a+)+, is matched against the body of each pattern, with or without a ^ before it and a $ after it, whatever its delimiters and modifiers: it skips /(a+)+$/, /(a+)+$/i, {(a+)+$} and #(a+)+$#u alike. A delimited pattern without modifiers, /(a+)+$/, is read by its body the same way. One written with modifiers names that pattern only, the same body under the same modifiers, in any order and between any delimiters: /(a+)+$/i skips #(a+)+$#i, not /(a+)+$/ or /(a+)+$/iu.

Using the service

The Regex facade forwards to the PHPRegex\Toolkit\Regex service the provider registers:

use PHPRegex\Laravel\Facades\Regex;

Regex::validate('/^[a-z0-9-]{3,}$/')->isValid; // true

$invalid = Regex::validate('/^(unclosed/');

$invalid->error; // "Expected ) at end of input (found eof)."
echo $invalid->caretSnippet;
// Line 1: ^(unclosed
//                   ^

Explain a pattern in plain English:

echo Regex::explain('/^\d{4}$/');
// Regex matches
//   Anchor: the start of the subject
//   Character Type: A digit [0-9], exactly 4 times
//   Anchor: the end of the subject, or just before a newline (\n) that ends it

Check one for ReDoS:

$analysis = Regex::redos('/^(a+)+$/');

$analysis->isSafe();                  // false
$analysis->severity->value;           // 'critical'
$analysis->vulnerablePart; // 'a+'
$analysis->headline();                // 'Exponential backtracking (proven)'
$analysis->witness->render();         // '"a" x n . "!"', the input that triggers it

The facade mirrors the whole service — create, fromOptions, parse, parseTolerant, parsePattern, parser, validate, analyze, lint, redos, optimize, transpile, explain, highlight, literals, captureShape, info, compatibility, generate, tokenize, target, getCache, getCacheStats and clearCaches; the API reference documents each. One of those bypasses the configured singleton: Regex::create() returns a fresh instance. Type-hinting PHPRegex\Toolkit\Regex injects the same service — no facade needed.

Validating a pattern a user submits

The ValidRegex rule accepts a value that PCRE compiles, written as preg_match() takes it: delimiters and flags included. The verdict is the one regex validate gives, judged by the Regex service with the limits of config/php-regex.php, so a pattern longer than max_pattern_length is refused too:

use PHPRegex\Laravel\Rules\ValidRegex;

$request->validate([
    'pattern' => ['required', new ValidRegex()],
    'route_pattern' => ['required', new ValidRegex(redos: true)],
]);
  • An invalid pattern fails with the library’s message: The pattern field must be a valid regular expression: Unmatched closing parenthesis at position 4. for /abc)/. A value that is no string fails as must be a string.
  • redos: true also refuses a pattern whose ReDoS severity reaches redosThreshold: low, medium, high (the default) or critical, as a string or a RedosSeverity. /x*x*x*$/ (polynomial, high) is refused, /a*a*$/ (medium) passes. An invalid pattern is never analysed for ReDoS.
  • Like every rule, it leaves an empty value to required.

The service and the lint judge for different targets

The Regex service runs in your application: it judges patterns for the PHP running it, under the locale it runs under, and php_version / pcre_version / locale do not change that: a request may run under another LC_CTYPE than the console.

regex:lint judges the patterns of your code for the PHP your project supports. It picks the target in this order:

  1. php_version and pcre_version in config/php-regex.php. A single version ("8.2", "8.2.4", 80200) is judged alone. A Composer constraint (">=8.1", "^8.1 <8.7") is judged as a require.php range: from its lowest PHP, then at every later PHP it allows, and the report names config php-regex.php_version as its source. A constraint that names no lowest version ("<8.4", "*"), or a PHP_VERSION_ID inside a constraint (">=80100"), stops the command with exit code 2 (see Naming a range). A single version hides the wider range composer.json allows: write ">=8.1", or leave the key null to read composer.json;
  2. composer.json at base_path(): config.platform.php if set, else the lowest version require.php allows, and then every pattern is also validated on the later PHP versions the constraint allows, as the standalone command does;
  3. the PHP running the command.

Each version is chosen on its own, and every version judged (the target, each later version of the range, each version a guard or a marker keeps) gets its PCRE2 in this order, the order of every entry point:

  1. pcre_version, else the release composer.json at base_path() pins in config.platform.lib-pcre ("10.42", or "10.42.0" as Composer spells it). A pin is used as is, older or newer than the one that PHP bundles;
  2. the PCRE2 of the PHP running the command, when the version judged is its minor version: on a PHP 8.4.27 that links 10.49, PHP 8.4 is judged with 10.49;
  3. the PCRE2 that PHP bundles: 10.32 for PHP 7.3, 10.33 for 7.4, 10.35 for 8.0, 10.39 for 8.1, 10.40 for 8.2, 10.42 for 8.3, 10.44 for 8.4 and 8.5.

A config.platform.lib-pcre that names no PCRE2 release is passed over with a notice.

The locale is locale, else the one of the PHP running the command (see Which locale judges a pattern): its character tables decide the size of a few classes, and one the machine cannot set stops the command. The console report shows the target in its header; the JSON report carries it as a top-level target object:

{
    "target": {"php": "8.2", "pcre": "10.40", "locale": "C", "source": "config php-regex.php_version", "range": [{"php": "8.2", "pcre": "10.40"}]},
    "stats": {"errors": 0, "warnings": 0, "optimizations": 0, "redos_errors": 0, "infos": 0, "lint_errors": 0, "parser_fallbacks": 0, "not_analyzed": 0, "arguments_constant": 0, "arguments_finite_set": 0, "arguments_quoted_shell": 0, "arguments_raw_shell": 0, "arguments_opaque": 0},
    "results": []
}

The report is the one vendor/bin/regex lint --format=json prints, and regex:transpile --format=json prints the same document as vendor/bin/regex transpile; the JSON output reference lists every key.

runtime_pcre_validation compiles with the PHP that runs, which cannot tell whether an older PHP accepts a pattern: the lint never uses it.

Commands

Command Description
regex:lint Lint the regex patterns of your PHP code
regex:compare Compare two patterns with automata
regex:explain Explain a pattern in plain English
regex:routes List and validate route constraints
regex:transpile Translate a pattern for another regex engine
php artisan regex:lint
php artisan regex:lint app/ --format=json
php artisan regex:compare '/[a-z]+/' '/edit/'
php artisan regex:compare '/[0-9]+/' '/\d+/' --method=equivalence
php artisan regex:transpile '/^[a-z]+$/' -t python
php artisan regex:transpile '/(?>a)b/' -t python --python-version=3.11

regex:lint writes its banner and its report on stdout. Its steps, their progress bars and an error that stops the run (Error: Path not found: app/Legacy) go to stderr, as regex lint writes them, so php artisan regex:lint > lint.txt keeps the report alone. The Symfony bundle and the Laravel package run the same lint, and print it the same way. Under -v the title names the author and the report ends on a request for a GitHub star.

Under its summary line, the report says how many pattern arguments of the PHP calls are built at run time, which no rule can verify, as regex lint says it:

  Not verifiable: 3 pattern arguments (1 dynamic, 1 around a dynamic part, 1 around preg_quote())

The line is left out when there is none (see Arguments built at run time). The command does not list them one by one: vendor/bin/regex lint --report-dynamic does.

Each command exits with 0 when it found nothing wrong, 1 when the patterns or the files it judged have a problem, and 2 when an option or the configuration cannot be used (see the CLI guide).

regex:compare --method takes the methods of regex compare and Symfony’s regex:compare, with the same default: intersection (do the two patterns share a string?), subset (is every string of the first one a string of the second?) and equivalence (do they match the same strings?). A failed check prints the string that proves it. A subset check that holds both ways says the patterns are equivalent, never that the first is a strict subset of the second. --format=json writes the verdict under a key named for the method: disjoint and example, subset and counterexample, or equivalent, counterexample, left_only_example and right_only_example; the keys of the other methods are there too, null.

regex:lint --jobs=N (or -j N) runs the analysis in N worker processes; left out, the count follows the CPUs (and the container’s memory limit). A --jobs that is not a whole number of 1 or more is refused with exit code 2, as regex lint and Symfony’s regex:lint refuse it, and so is a --min-savings that is not a whole number of 0 or more (The --min-savings value must be a non-negative integer.). So is a path that does not exist: Path not found: app/Legacy, stage usage in the JSON envelope for a path given on the command line, config for one of php-regex.paths, which the message names.

The commands take the options of the same command in the CLI and in the Symfony bundle, under the same names and short forms (-j for --jobs, -t for --target). What stays Laravel’s own: regex:routes lists and validates route constraints, where Symfony’s analyzes the conflicts between routes, and there is no regex:security or regex:analyze, which read Symfony’s router and security.yaml.

regex:routes lists the routes that have a constraint. --show-constraints prints each constraint, and --validate compiles each one as the router matches it, marking it ✓ or ✗ with the error: without --validate a constraint gets no mark, and its valid key in the JSON report is null. The JSON output reference lists every key of the regex:routes and regex:compare reports.

regex:compare, regex:transpile and regex:explain --highlight colour a pattern only on a terminal: piped, or under --no-ansi, it is printed as plain text.

regex:lint reads the functions marked #[RegexPattern] (or PhpStorm’s #[Language('RegExp')]) in the configured paths, with exclude where they are linted, the linted paths when paths names none, and in the application’s vendor/, whatever exclude says; a project declaration wins over a copy in vendor/. A call to one is linted as a preg_*() call (see the CLI guide); every rule it can report is catalogued in Lint rules.

A regex: or not_regex: validation rule is linted as Laravel’s validator reads it. A rules string is split on every |, one inside the pattern included: 'code' => 'required|regex:/^(?:a|b)$/' hands /^(?:a to preg_match(), and the lint reports it as invalid. Write such a rule as an array element, ['required', 'regex:/^(?:a|b)$/'], which keeps its |. The rules a call takes are a rules string too, given by position or by name: $validator->sometimes('code', 'regex:/^(a|b)$/', …), the $rules and $defaultRules of Rule::when() and Rule::unless(), and those of new ConditionalRules() are split. So is each string element of the array Rule::anyOf() takes (Laravel 12.8 and later), which the rule validates alone: Rule::anyOf(['regex:/^(a|b)$/']) hands /^(a to preg_match(), where Rule::anyOf([['regex:/^(a|b)$/']]) keeps its |. The rule of Livewire’s #[Rule] (Livewire 3.0 and later) or #[Validate] (3.2 and later) is the rules string of the property it marks: #[Validate('regex:/^(a|b)$/')] hands /^(a to preg_match(), and so does the key of the rules an attribute is given keyed, #[Validate(['code' => 'regex:/^(a|b)$/'])]. Livewire merges the rules all the attributes of a component give, though: where two of them give rules to one key, whatever property each marks, that key holds one list, each string is one rule, and 'nullable|regex:/^a$/' is one rule Laravel names nullable|regex. A string another call takes is one rule: array_push($rules['code'], 'regex:/^(a|b)$/') appends one element, and one element with a rule before the regex one, 'nullable|regex:/^a$/', is a rule Laravel names nullable|regex, which runs no pattern. The pattern is linted as written, between any delimiter PHP takes: {^a$} is the pattern between braces, not /{^a$}/, and a double-quoted literal as PHP decodes it: "regex:/^[\u{0600}-\u{06FF}]+$/u" holds the characters PHP decodes, not \u, "required|\tregex:/^a$/" a tab before the rule’s name and "regex\x3a/^a$/" the rule’s :. Only the string literals of the PHP code are read: a quoted rule in a comment, in the text of a heredoc or a nowdoc, or in the text around the PHP tags is none. A heredoc is read as PHP decodes it, a nowdoc as written, where the code says it holds rules: given to a key, assigned, or taken by a call as rules. Literals joined with . are the one string PHP builds: 'regex:/^(a' . 'b)$/' runs /^(ab)$/, not /^(a, and an operand that is no literal is read as an expression of an interpolated string. In a double-quoted rules string that interpolates, a rule between two | of its text is read, "min:$min|regex:/^a$/" runs /^a$/, and one an expression is part of, "regex:/^{$prefix}-\d+$/", is not: only the running code knows its pattern. The rule’s name is read without case, as Laravel reads it, and notregex: is not_regex:. A name with blanks around it, 'required | regex:/^a$/', is still the regex rule, but Laravel then reads its parameter as comma-separated values and runs the first one: ' regex:/^a{1,2}$/' runs /^a{1, and that is what is linted.

A route constraint is judged as the router compiles it: stripped of a leading ^ or \A and a trailing $ or \z, its groups made non-capturing, in a group named after the parameter, between braces and under the s, D and u flags Laravel’s route compiler adds (and i for a domain parameter). ->where('v', '(a+)+') is linted as {^(?P<v>(?:a+)+)$}sDu, so its backtracking is reported; the flags the router adds are never a finding, since the constraint cannot remove them. A constraint that compiles alone but breaks the route is invalid: [{] leaves the router’s braces unbalanced, a\$ loses its $ and escapes the group’s ), and (a)(b)\2 refers to a group that no longer captures.

ReDoS findings

With 'redos' => ['enabled' => true], regex:lint adds the ReDoS issue, regex.lint.redos, to the findings of each pattern at or above redos.threshold:

  ./app/Validator.php:7:33
      → /^(\w+\s?)+$/
     ...
     WARN  Exponential backtracking (proven). Severity: CRITICAL, confidence: MEDIUM.
         ↳ Attack: "0" x n . "!" Unbounded quantifier detected. May cause backtracking on non-matching input. ...

  ./app/Validator.php:12:33
      → /\d*\d*\d*$/
     ...
     WARN  Polynomial backtracking, degree 3 (proven). Severity: HIGH, confidence: MEDIUM.
         ↳ Attack: "0" x n . "!" Adjacent quantified tokens with overlapping character sets can cause ambiguous backtracking ...

regex:explain ends its explanation with a security warning when the pattern is at risk, and prints nothing more for a safe one:

php artisan regex:explain '/(a+)+$/'
Security Warning:
  Exponential backtracking (proven)
  Severity: critical
  Attack: "a" x n . "!"
  Vulnerable part: a+
  Recommendations:
    - Unbounded quantifier detected. May cause backtracking on non-matching input. ...
    - Nested unbounded quantifiers detected. This allows exponential backtracking. ...

The first line is the verdict’s headline, then its severity; Attack is the input that drives the worst case, as PHP: str_repeat("a", $n) . "!". A pattern the structural heuristics judge, such as one with a backreference, shows Potential backtracking (heuristic) and no attack. The ReDoS guide explains each verdict.

With --format=html the explanation is HTML, and every text the report takes from the pattern, the pattern itself, the optimization, the security warning, the lint issues, the sample and an error, is HTML-encoded: /<b>/ is printed /&lt;b&gt;/, so the page that shows the report never renders a tag the pattern holds. Highlighting is for the console format only.

Upgrading from 1.x

2.0 renames or removes three keys — and the REGEX_PARSER_IDE env var becomes PHP_REGEX_IDE. A leftover 1.x key is silently ignored (no warning is printed), so move each one over by hand:

1.x key 2.0
exclude_paths exclude
analysis.ignore_patterns merged into redos.ignored_patterns
analysis.redos_threshold removed (it was never read)
REGEX_PARSER_IDE PHP_REGEX_IDE (APP_EDITOR unchanged)

redos.enabled now makes regex:lint report ReDoS findings: 1.x never ran the analysis, whatever the setting. Expect new warnings on the first run.

Re-publish the file to pick up the new keys and comments:

php artisan vendor:publish --tag=php-regex-config --force

See UPGRADE-2.0.md for the rest.

Edit on GitHub Feedback