我有一个网站,其中包含一个搜索框,允许用户输入一个模式,然后对照大字符串进行检查,以查看这些字符串中是否存在与用户指定的模式匹配的任何匹配项。这是使用 PHP 函数完成的preg_match()。
然而,当用户输入无效模式时就会出现问题,例如导致错误的模式,例如:
preg_match() [function.preg-match]:未知修饰符。
搜索功能需要能够处理该preg_match()方法引发的任何错误,并在屏幕上显示一般模式无效消息。我在网上查看过,但找不到一种捕获任何preg_match()可能抛出的错误的一揽子方法,有人有任何想法吗?
举一个简单的例子,设置一个错误处理程序并抛出一个Exceptionor ErrorException:
function exception_error_handler($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler("exception_error_handler");
Run Code Online (Sandbox Code Playgroud)
然后尝试/捕获:
try {
preg_match('/.*/hello', 'hello');
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Run Code Online (Sandbox Code Playgroud)
捕获异常:preg_match():未知修饰符“h”