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

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

The PCRE extension provides functions that allow 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 in PHP preg_ functions, such as preg_match, preg_replace, doesn't throw an exception if an error occurs during execution. Error can be manually inspected by using the preg_last_error function, which returns an error code.

<?php

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

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

2

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

<?php

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

Example will output:

Backtrack limit exhausted

Leave a Comment

Cancel reply

Your email address will not be published.