我如何判断给定的字符串是否是PHP';s preg_match


How can I tell if a given string is a valid input to PHP's preg_match?

我正在构建一个管理UI,用户可以在其中管理一个列表PCRE字符串,这些字符串在我的应用程序的其他点传递给PHP的preg_match

在存储用户的输入以供preg_match稍后使用之前,我首先要验证用户的输入是否是有效的PCRE表达式,否则稍后将其传递给preg_match会引发错误。

在PHP中,验证给定字符串以查看它是否是有效的PCRE的最佳方法是什么?

您的最佳选择是将字符串传递给preg_match,并捕获发生的任何错误。

try{
    preg_match($in_regex, $string, $results);
    //Use $results
} catch (Exception $e) {
    echo "Sorry, bad regex (/" . $in_regex . "/)";
}

[编辑]既然这不起作用,你可以试试:

function bad_regex($errno, $errstr, $errfile, $errline){
    echo "Sorry, bad regex.";
}
set_error_handler("bad_regex");
preg_match($in_regex, $string, $results);
restore_error_handler();