Function name: preg_last_error_msg()
Applicable version: PHP 8.0.0 and above
Function Description: The preg_last_error_msg() function is used to obtain the error information of the last PCRE regular expression function call.
Syntax: string preg_last_error_msg( void )
Return value: Returns a string describing the last PCRE error, and if no error occurs, an empty string is returned.
Example:
<?php // 示例1 preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches); if (preg_last_error() !== PREG_NO_ERROR) { echo preg_last_error_msg(); } else { echo "No error occurred."; } // 输出:No error occurred. // 示例2 preg_match('/(foo)(bar)(baz/', 'foobarbaz', $matches); if (preg_last_error() !== PREG_NO_ERROR) { echo preg_last_error_msg(); } // 输出:PREG_BAD_DELIMATOR - missing ending delimiter '/' // 示例3 preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_UNMATCHED_AS_NULL); if (preg_last_error() !== PREG_NO_ERROR) { echo preg_last_error_msg(); } else { echo "No error occurred."; } // 输出:No error occurred. ?>
The above example shows the usage of the preg_last_error_msg() function. In Example 1, the regular expression has no errors, so the function returns an empty string. In Example 2, the regular expression lacks an end delimiter, resulting in a PREG_BAD_DELIMATOR error and obtains the error message through the preg_last_error_msg() function. In Example 3, the PREG_UNMATCHED_AS_NULL option was used, but the regular expression has no errors, so the function returns an empty string.
Note that in order to use the preg_last_error_msg() function, error checking must be done immediately after the function is called, because the function only returns the error message for the last PCRE function call.