The preg_last_error Function
The preg_last_error
function returns the code of the last error,
that occurred while working with regular expression functions.
This is useful for debugging regular expressions when functions
like preg_match
or preg_replace
return false
.
The function does not accept any parameters.
The function returns an integer error code. For convenience, the error code can be compared with special constants (see the table below).
Syntax
preg_last_error(): int;
Error Constants Table
Constant | Value | Description |
---|---|---|
PREG_NO_ERROR |
0 | No errors occurred |
PREG_INTERNAL_ERROR |
1 | Internal PCRE error |
PREG_BACKTRACK_LIMIT_ERROR |
2 | Backtrack limit was exhausted |
PREG_RECURSION_LIMIT_ERROR |
3 | Recursion limit was exceeded |
PREG_BAD_UTF8_ERROR |
4 | Malformed UTF-8 data |
PREG_BAD_UTF8_OFFSET_ERROR |
5 | The offset did not correspond to the beginning of a valid UTF-8 code point |
PREG_JIT_STACKLIMIT_ERROR |
6 | JIT stack limit was exceeded |
Example
Let's check the error after an invalid regular expression:
<?php
preg_match('/invalid(regex/', 'test');
$error_code = preg_last_error();
echo $error_code;
?>
Code execution result:
4
Example
Usage with PCRE error constants:
<?php
preg_match('/(?:\D+/', 'abc123');
if (preg_last_error() === PREG_BACKTRACK_LIMIT_ERROR) {
echo 'Backtrack limit was exhausted';
}
?>
Code execution result:
'Backtrack limit was exhausted'
See Also
-
the
preg_match
function,
which performs a regular expression match -
the
preg_replace
function,
which performs a regular expression search and replace -
the
preg_quote
function,
which escapes special characters in regular expressions