我需要检查字符串是否为有效的正则表达式。
有没有办法做到这一点,而不会有性能问题?
N。B:我想在使用它之前检查它,preg_last_error()不是我要找的。
建议的preg_last_error
不会为您工作,因为它只返回PCRE运行时错误,而不是编译错误-在后一种情况下,您得到的只是php警告("编译失败")。解决这个问题的一种干净的方法是安装一个error-to-exception错误处理程序,然后在try-catch块中编译模式:
try {
preg_match($pattern, "...");
} catch(ErrorException $e) {
// something is wrong with the pattern
}
最好的方法通常是尝试使用Regex引擎运行/编译它并检查错误。在你需要之前,我不会担心性能
在php中,我使用以下函数来测试pcre的有效性:
function BoolTestPregRegex($Regex)
{
$Result = @preg_match("/$Regex/", '1234567890123');
if ($Result === false)
return false;
else
return true;
}