Regex Performance in PHP
Compile-once with preg_quote for dynamic patterns, avoid catastrophic backtracking, and use atomic groups or possessive quantifiers for critical paths.
Compile-once with preg_quote for dynamic patterns, avoid catastrophic backtracking, and use atomic groups or possessive quantifiers for critical paths.
<?php
// Escape user input before using in regex
$userInput = "foo.bar+baz";
$escaped = preg_quote($userInput, "/");
// "foo\.bar\+baz"
preg_match("/{$escaped}/", $haystack);
// Avoid catastrophic backtracking:
// BAD: nested quantifiers
// preg_match("/^(a+)+$/", str_repeat("a", 30) . "b"); // Very slow!
// GOOD: possessive quantifier (PHP 8+) or atomic group
// preg_match("/^(?>a+)+$/", ...); // Atomic group
// preg_match("/^a++$/", ...); // Possessive quantifier
// Limit matches to avoid runaway
preg_match_all("/\w+/", $input, $m, 0, 0, 1000); // limit to 1000 matches
Use preg_quote() whenever building a regex from user-provided strings to prevent regex injection attacks.