我想在PHP中测试正则表达式的有效性,最好在它使用之前.这样做的唯一方法是尝试preg_match()并查看它是否返回FALSE?
有没有更简单/正确的方法来测试有效的正则表达式?
Cod*_*gry 127
// This is valid, both opening ( and closing )
var_dump(preg_match('~Valid(Regular)Expression~', null) === false);
// This is invalid, no opening ( for the closing )
var_dump(preg_match('~InvalidRegular)Expression~', null) === false);
Run Code Online (Sandbox Code Playgroud)
正如用户poz所说,还要考虑@@preg_match()在测试环境中放置preg_match()()以防止出现警告或通知.
要验证RegExp,只需对其进行运行null (无需知道要预先测试的数据).如果它返回显式的false(=== false),它就会被破坏.否则它是有效的,虽然它不需要匹配任何东西.
因此,无需编写自己的RegExp验证器. 浪费时间......
Wah*_*nto 23
我创建了一个简单的函数,可以调用preg来调用
function is_preg_error()
{
$errors = array(
PREG_NO_ERROR => 'Code 0 : No errors',
PREG_INTERNAL_ERROR => 'Code 1 : There was an internal PCRE error',
PREG_BACKTRACK_LIMIT_ERROR => 'Code 2 : Backtrack limit was exhausted',
PREG_RECURSION_LIMIT_ERROR => 'Code 3 : Recursion limit was exhausted',
PREG_BAD_UTF8_ERROR => 'Code 4 : The offset didn\'t correspond to the begin of a valid UTF-8 code point',
PREG_BAD_UTF8_OFFSET_ERROR => 'Code 5 : Malformed UTF-8 data',
);
return $errors[preg_last_error()];
}
Run Code Online (Sandbox Code Playgroud)
您可以使用以下代码调用此函数:
preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar');
echo is_preg_error();
Run Code Online (Sandbox Code Playgroud)
替代方案 - 正则表达式在线测试仪
Ali*_*aru 15
如果你想动态测试一个正则表达式preg_match(...) === false似乎是你唯一的选择.PHP没有在使用前编译正则表达式的机制.
您也可以发现preg_last_error是一个有用的函数.
另一方面,如果你有一个正则表达式,并且只是想在使用它之前知道它是否有效,那么有很多工具可用.我发现rubular.com使用起来很愉快.
如果您的引擎支持递归(PHP应该),您可以检查它是否是正则规则正确的正则表达式与正则表达式的恶梦.
但是,不能通过算法判断它是否会在不运行的情况下提供所需的结果.
From:是否有正则表达式来检测有效的正则表达式?
/^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/
Run Code Online (Sandbox Code Playgroud)