preg_last_error
Returns the error code generated by the last PCRE regular execution
preg_last_error()
function returns the error code for the recently evaluated regular expression. The returned value will match one of the following constants:
constant | describe |
---|---|
PREG_NO_ERROR | No error occurred. |
PREG_INTERNAL_ERROR | An error occurred while evaluating the expression. |
PREG_BACKTRACK_LIMIT_ERROR | The number of backtraces required to evaluate an expression exceeds the limit given in the PHP configuration. |
PREG_RECURSION_LIMIT_ERROR | The recursion depth required to evaluate an expression exceeds the limits given in the PHP configuration. |
PREG_BAD_UTF8_ERROR | The input string contains invalid UTF-8 data. |
PREG_BAD_UTF8_OFFSET_ERROR | During evaluation, the string offset does not point to the first character of the multibyte UTF-8 symbol. |
PREG_JIT_STACKLIMIT_ERROR | The JIT compiler exhausts stack memory while trying to evaluate expressions. |
Use preg_last_error()
to handle errors:
<?php $str = 'This regular expression is invalid. ' ; $pattern = '/invalid//' ; $match = @ preg_match ( $pattern , $str , $matches ) ; if ( $match === false ) { // An error occurred $err = preg_last_error ( ) ; if ( $err == PREG_INTERNAL_ERROR ) { echo 'regex is invalid. ' ; } } else if ( $match ) { // Find a match echo $matches [ 0 ] ; } else { // No match found echo 'No match found' ; } ?>
preg_last_error ( )