测试字符串是否为正则表达式


Test if a string is regex

有没有很好的方法来测试字符串是PHP中的正则表达式还是普通字符串?

理想情况下,我想编写一个函数来运行一个返回 true 或 false 的字符串。

我看了一下preg_last_error()

<?php
preg_match('/[a-z]/', 'test');
var_dump(preg_last_error());
preg_match('invalid regex', 'test');
var_dump(preg_last_error());
?>

显然第一个不是错误,第二个是错误。但preg_last_error()两次都int 0回来了。

有什么想法吗?

测试字符串是否为正则表达式的最简单方法是:

if( preg_match("/^'/.+'/[a-z]*$/i",$regex))

这将告诉您字符串是否很有可能作为正则表达式。但是,有许多字符串可以通过该检查,但无法成为正则表达式。中间的未转义斜杠、末尾的未知修饰符、不匹配的括号等都可能导致问题。

返回 0 preg_last_error原因是因为"无效正则表达式"不是:

  • PREG_INTERNAL_ERROR(内部错误)
  • PREG_BACKTRACK_LIMIT_ERROR(过度强制回溯)
  • PREG_RECURSION_LIMIT_ERROR(过度递归)
  • PREG_BAD_UTF8_ERROR(UTF-8 格式错误)
  • PREG_BAD_UTF8_OFFSET_ERROR(偏移到 UTF-8 字符的中间)

这是一个很好的答案:

https://stackoverflow.com/a/12941133/2519073

if(@preg_match($yourPattern, null) === false){
    //pattern is broken
}else{
    //pattern is real
}

测试正则表达式在 PHP 中是否有效的唯一简单方法是使用它并检查是否抛出警告。

ini_set('track_errors', 'on');
$php_errormsg = '';
@preg_match('/[blah/', '');
if($php_errormsg) echo 'regex is invalid';

但是,使用任意用户输入作为正则表达式是一个坏主意。PCRE引擎之前存在安全漏洞(缓冲区溢出=>远程代码执行),并且有可能创建需要大量CPU/内存才能编译/执行的特制长正则表达式。

为什么不直接使用...另一个正则表达式? 三行,没有@的混乱或任何东西:

// Test this string
$str = "/^[A-Za-z ]+$/";
// Compare it to a regex pattern that simulates any regex
$regex = "/^'/['s'S]+'/$/";
// Will it blend?
echo (preg_match($regex, $str) ? "TRUE" : "FALSE");

或者,在函数形式中,甚至更漂亮:

public static function isRegex($str0) {
    $regex = "/^'/['s'S]+'/$/";
    return preg_match($regex, $str0);
}

这并不测试有效性;但看起来这个问题Is there a good way of test if a string is a regex or normal string in PHP?,它确实做到了。