PHP preg_last_error() Function
The PHP preg_last_error() function returns the error code of the last PCRE regex execution.
Syntax
preg_last_error()
Parameters
No parameter is required.
Return Value
Returns one of the following constants:
Constants | Description |
---|---|
PREG_NO_ERROR | There were no errors. |
PREG_INTERNAL_ERROR | There was an internal PCRE error. |
PREG_BACKTRACK_LIMIT_ERROR | The backtrack limit was exhausted. |
PREG_RECURSION_LIMIT_ERROR | The recursion limit was exhausted. |
PREG_BAD_UTF8_ERROR | The last error was caused by malformed UTF-8 data (only when running a regex in UTF-8 mode). |
PREG_BAD_UTF8_OFFSET_ERROR | The offset didn't correspond to the begin of a valid UTF-8 code point (only when running a regex in UTF-8 mode). |
PREG_JIT_STACKLIMIT_ERROR | The last PCRE function failed due to limited JIT stack space. |
Example: preg_last_error() example
The example below shows the usage of preg_last_error() function.
<?php $string = 'May 25, 2005'; //invalid pattern - missing ending delimiter $pattern = '/May'; $match = @preg_match($pattern, $string, $matches); if($match === false) { //an error occurred - getting the last error $err = preg_last_error(); if($err == PREG_INTERNAL_ERROR) { echo 'Invalid regular expression.'; } } else if($match) { //a match was found echo $matches[0]; } else { //no matches were found echo 'No matches found'; } ?>
The output of the above code will be:
Invalid regular expression.
Example: backtrack limit exhaustion
Consider one more example, where this function is used to get the last PCRE regex execution error which was backtrack limit exhaustion.
<?php preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar'); if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR) { echo 'Backtrack limit was exhausted!'; } ?>
The output of the above code will be:
Backtrack limit was exhausted!
❮ PHP RegEx Reference