PHP Function Reference

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:

ConstantsDescription
PREG_NO_ERRORThere were no errors.
PREG_INTERNAL_ERRORThere was an internal PCRE error.
PREG_BACKTRACK_LIMIT_ERRORThe backtrack limit was exhausted.
PREG_RECURSION_LIMIT_ERRORThe recursion limit was exhausted.
PREG_BAD_UTF8_ERRORThe last error was caused by malformed UTF-8 data (only when running a regex in UTF-8 mode).
PREG_BAD_UTF8_OFFSET_ERRORThe 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_ERRORThe 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