In PHP, preg_last_error() returns an integer code for the last PCRE error from a preg_* function.
After a failed call (bad pattern, backtrack limit, recursion limit, and similar), the code is not PREG_NO_ERROR. Compare it with constants such as PREG_INTERNAL_ERROR or PREG_BACKTRACK_LIMIT_ERROR.
Syntax
Call preg_last_error() with the values you need. Start with this line.
PHP
$code = preg_last_error();
Call
What it does
preg_last_error()
Returns PREG_NO_ERROR (0) when the last preg_* call succeeded.
preg_last_error() === PREG_NO_ERROR
True when there was no PCRE error.
preg_last_error() === PREG_INTERNAL_ERROR
True after some failures, such as a broken pattern.
Call preg_last_error() right after a preg_* function returns false or null unexpectedly. For a readable message, use preg_last_error_msg() instead of memorizing every code.
Library declarations
PHP
preg_last_error(): int
Parameters
Parameter
Description
—
This function takes no parameters.
Return Value
Return Value
Description
int
A PCRE error code. PREG_NO_ERROR (0) means the last operation had no error.
First call uses a broken pattern and sets a non-zero error code.
Second call uses a valid pattern and succeeds.
preg_last_error() is now 0 again.
Always read the error immediately after the call you care about.
Frequently Asked Questions
It returns an integer code describing the last error from a preg_* function. 0 (PREG_NO_ERROR) means no error.
When a preg_* function returns false or null and you need to know why — for example a bad pattern or a backtrack limit.
No. No match returns int 0. false means an error occurred. Use preg_last_error() to inspect that error.
It means the match needed more backtracking steps than PHP allows. Complex or “evil” patterns on long strings can trigger it. Simplify the pattern or raise the limit carefully.
Use preg_last_error_msg(). It returns a short string for the same last error that preg_last_error() reports as a code.