Get Error Message of the Last PCRE Regex Execution in PHP 8.0

The PCRE extension provides functions that allows to perform a regular expression (regex) matching operations. A regular expression is defined using the same syntax as Perl 5. This extension is included in PHP core.

A regular expression PHP preg_ functions, such as preg_match, preg_replace, doesn’t throw exeception if error occurs during execution. Error can be manually inspected by using preg_last_error function which returns an error code.


preg_match('/(\D+)+[\d]/', 'hello hello hello hello');
echo preg_last_error();

Example will output 2. It means that backtrack limit was reached.


Since PHP 8.0, we can use a new preg_last_error_msg function which allows to get an error message of the last PCRE regular expression execution.


preg_match('/(\D+)+[\d]/', 'hello hello hello hello');
echo preg_last_error_msg();

Example will output:

Backtrack limit exhausted

Leave a Comment

Your email address will not be published. Required fields are marked *