29

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

理想情况下,我想编写一个函数来运行一个字符串,它返回真或假。

我看了看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

有任何想法吗?

4

4 回答 4

16

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

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 字符的中间)
于 2012-05-28T00:57:23.653 回答
15

这是一个很好的答案:

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

if(@preg_match($yourPattern, null) === false){
    //pattern is broken
}else{
    //pattern is real
}
于 2015-04-07T14:39:21.980 回答
10

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

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

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

于 2012-05-28T00:59:53.720 回答
9

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

// 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?,它确实做到了。

于 2013-04-19T05:52:55.250 回答