How to Returns an error code indicating the reason that the most recent regular expression call failed in PHP ?


In PHP, we can use the preg_last_error() function to return an error code indicating the reason that the most recent regular expression call failed.

The preg_last_error() function returns an integer value that corresponds to one of the predefined error constants in PHP. These constants are:

  • PREG_NO_ERROR: No error occurred.
  • PREG_INTERNAL_ERROR: There was an internal PCRE error.
  • PREG_BACKTRACK_LIMIT_ERROR: Backtrack limit was exhausted.
  • PREG_RECURSION_LIMIT_ERROR: Recursion limit was exhausted.
  • PREG_BAD_UTF8_ERROR: The last error was caused by malformed UTF-8 data.
  • PREG_BAD_UTF8_OFFSET_ERROR: The last error was caused by a UTF-8 offset that does not correspond to the beginning of a valid UTF-8 code point.
  • PREG_JIT_STACKLIMIT_ERROR: The last error was caused by the PCRE JIT stack limit being exhausted.

Here's an example of how to use preg_last_error() function:

$pattern = '/[a-z]+/';
$string = '123';

if (preg_match($pattern, $string) === false) {
    $error_code = preg_last_error();
    switch ($error_code) {
        case PREG_INTERNAL_ERROR:
            echo "Internal PCRE error occurred";
            break;
        case PREG_BACKTRACK_LIMIT_ERROR:
            echo "Backtrack limit was exhausted";
            break;
        case PREG_RECURSION_LIMIT_ERROR:
            echo "Recursion limit was exhausted";
            break;
        case PREG_BAD_UTF8_ERROR:
            echo "Malformed UTF-8 data";
            break;
        case PREG_BAD_UTF8_OFFSET_ERROR:
            echo "Invalid UTF-8 offset";
            break;
        case PREG_JIT_STACKLIMIT_ERROR:
            echo "PCRE JIT stack limit was exhausted";
            break;
        default:
            echo "Unknown error occurred";
            break;
    }
}

In this example, we first attempt to match the regular expression pattern /[a-z]+/ against the string '123' using the preg_match() function. If the function returns false, we use the preg_last_error() function to get the error code and then use a switch statement to determine the reason for the error.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.