dongmaoxi0477 2013-07-03 19:34
浏览 48
已采纳

preg_match()错误尝试匹配变量[重复]

This question already has an answer here:

I keep getting an error when using this and I am not sure why. Any help would be amazing. I have Googled it and found examples but I get the error even with other peoples examples.

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

I also tried this and neither work:

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

The error I get is:

Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 0

When I echo out the $statement I get: "/Who/i" (without the quotes)

</div>
  • 写回答

1条回答 默认 最新

  • dtn913117 2013-07-03 19:38
    关注

    Make sure that whatever's in $statement will actually produce a VALID regex, e.g.

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

    will actually produce the regex

    /(a|/
    

    which is invalid, because there's no closing ) to finish off the capture group. You can get around this with:

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

    which will escape any regex metacharacters so you produce a valid regex in the end.

    Essentially, you're probably suffering from the regex equivalent of an SQL injection attack.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源