PHP Function Reference

PHP preg_last_error_msg() Function



The PHP preg_last_error_msg() function returns the error message of the last PCRE regex execution.

Note: This function is available as of PHP 8.0.0.

Syntax

preg_last_error_msg()

Parameters

No parameter is required.

Return Value

Returns the error message on success, or "No error" if no error has occurred.

Example: preg_last_error_msg() example

The example below shows the usage of preg_last_error_msg() function.

<?php
$string = 'May 25, 2005';

//invalid pattern - missing ending delimiter
$pattern = '/May';

$match = @preg_match($pattern, $string, $matches);

if(preg_last_error() !== PREG_NO_ERROR) {
  //if error occurred display 
  //the error message
  echo preg_last_error_msg();
} 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:

Internal error

Example: backtrack limit exhaustion

Consider one more example, where this function is used to get the last PCRE regex execution error message which was backtrack limit exhaustion.

<?php
preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar');

if (preg_last_error() !== PREG_NO_ERROR) {
  echo preg_last_error_msg();
}
?>

The output of the above code will be:

Backtrack limit exhausted

❮ PHP RegEx Reference