PHP › Regular Expressions in PHP
What is catastrophic backtracking in regular expressions, and how can a poorly constructed pattern cause a severe performance problem or even hang a PHP application?
AdvancedAnswer
Catastrophic backtracking occurs when a regular expression pattern containing nested or ambiguous repetition, such as multiple overlapping quantifiers that could match the same text in many different possible ways, is applied to certain input strings, causing the regular expression engine to explore an enormous, exponentially growing number of possible matching combinations before finally failing, which can consume massive amounts of processing time and effectively hang the application, making it important to carefully design patterns, particularly those handling user supplied input, to avoid this kind of ambiguous, deeply nested repetition.
// Potentially catastrophic pattern with nested quantifiers
// preg_match('/^(a+)+$/', $userInput);
// A carefully crafted malicious input could cause this to hangReal-world example A security review flags a regular expression pattern used to validate user input as vulnerable to catastrophic backtracking, and the team rewrites the pattern using a more carefully constrained, unambiguous structure to eliminate the risk of a malicious input causing a denial of service.