Why This Happens
PCRE has a backtrack limit to prevent catastrophic backtracking from hanging the process. When a complex pattern with nested quantifiers processes a long string, the number of possible paths can grow exponentially. The default limit of 1,000,000 backtracks is reached and preg_match returns false.
The Problem
$pattern = '/^(a+)+$/';
$input = str_repeat('a', 30) . 'b';
$result = preg_match($pattern, $input); // Catastrophic backtrackingThe Fix
// Fix 1: Simplify the pattern
$pattern = '/^a+$/';
// Fix 2: Use possessive quantifier
$pattern = '/^(a++)$/';
// Always check for errors:
$result = preg_match($pattern, $input);
if ($result === false) {
throw new RuntimeException('Regex error: ' . preg_last_error_msg());
}Step-by-Step Fix
- 1
Check for nested quantifiers
Look for patterns like (a+)+ or (.*)* that cause exponential backtracking. Simplify or flatten them.
- 2
Use possessive quantifiers
Add + after quantifiers (a++ instead of a+) to prevent backtracking, or use atomic groups (?>...) for the same effect.
- 3
Check preg_last_error
Always check the return value of preg_match. A false return means an error occurred. Use preg_last_error_msg() for details.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free