我正在编写一个 PHP 脚本,它接受来自用户的正则表达式模式,该模式由 preg_match() 使用。如何检查模式是否有效?
最佳答案
根据docs ,
preg_match() returns FALSE if an error occurred.
问题是它也会发出警告。
处理此问题的一种方法是抑制错误消息的输出,捕获返回值,如果错误为假,则使用 error_get_last()
输出错误。
有点像
$old_error = error_reporting(0); // Turn off error reporting
$match = preg_match(......);
if ($match === false)
{
$error = error_get_last();
echo $error["message"];
}
error_reporting($old_error); // Set error reporting to old level
在生产环境中您可能不需要错误报告位 - 这取决于您的设置。
关于php - 如何捕获无效的 preg_match 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3710454/