preg_match()尝试匹配变量时出错

时间:2013-07-03 19:34:08

标签: preg-match php

我在使用时遇到错误,我不知道为什么。任何帮助都会很棒。我用Google搜索并找到了示例,但即使是其他人的例子,我也会收到错误。

$statement = $list[$i];
echo $statement;
preg_match("/$statement/i", $q)

我也试过这个并且都没有工作:

$statement = '/' . $list[$i] . '/i';
echo $statement;
preg_match($statement, $q)

我得到的错误是:

  

警告:preg_match()[function.preg-match]:编译失败:在偏移量0处不重复

当我回复$statement时,我得到:"/Who/i"(不带引号)

1 个答案:

答案 0 :(得分:3)

确保$statement中的任何内容实际上都会生成VALID正则表达式,例如

$statement = '(a|'; // note lack of closing )
preg_match("/$statement/", $text);

实际上会产生正则表达式

/(a|/

这是无效的,因为没有关闭)来完成捕获组。你可以通过以下方式解决这个问题:

$statement = preg_quote('(a|');
             ^^^^^^^^^^

将转义任何正则表达式元字符,以便最终生成有效的正则表达式。

基本上,你可能正在遭受与SQL注入攻击相当的正则表达式。