【问题标题】:Warning: preg_match(): Unknown modifier '&lt;'警告:preg_match():未知修饰符 '<'
【发布时间】:2015-12-29 22:59:41
【问题描述】:

我正在尝试运行我在在线 php 正则表达式测试网站上调试的正则表达式。

这是完整的正则表达式:

$rule = '/[\s\S]*<(b|strong)>[\s\S]*notes:[\s\S]*<(\/b|\/strong)>([\s\S]*?)<(b|strong)>(sources|source|citation|data sources|last update)[\s\S]*/im';

即使使用更简单的测试正则表达式:

$rule = "/[\s\S]*<(b|strong)>[\s\S]*/im";

我仍然从这段代码中得到一个错误:

$matches = array();
preg_match($source_html, $rule, $matches);

我收到的错误是:

警告:preg_match(): 未知修饰符 '<'在 .../FragmentGrabber.php 第 63 行

我在我的本地盒子上试图解决这个问题。无论如何要解决此警告并让我的正则表达式正常工作。我已经尝试修复我的正则表达式的转义字符,但这没有帮助。也许存在字符编码问题?!请注意输出中的文字 &amp;lt;&amp;lt;

编辑:

这是我班的一个sn-p,如果有人真的想要,我会发布整个内容。

  // d() below is the Kint debugger.
  public function get_fragments_by_name($source_html, $name)
  {
    $matches = array();
    $rule = self::generate_regex_rule($name);
    preg_match($source_html, $rule, $matches);
    return $matches;
  }

  private function generate_regex_rule($name)
  {
    $end_tags = self::get_end_tag_options($name);
    $rule = "/[\s\S]*<(b|strong)>[\s\S]*/";# . $name . ":[\s\S]*<(\/b|\/strong)>([\s\S]*?)<(b|strong)>(" . $end_tags . ")[\s\S]*/im";
    d($rule);
    return $rule;
  }

【问题讨论】:

  • 这显然不是导致崩溃的真正源代码。从错误消息中可以看出,有些东西将您的&amp;lt; 转换为&amp;lt;,因此 html 特殊字符替换。这不是偶然或隐含的。请出示您的真实代码。
  • 好的,请看我的编辑。如果你想要 Gist 或其他内容,我可以向你展示整个代码,但它的 126 LOC 我不喜欢通常粘贴代码墙。

标签: php regex


【解决方案1】:

preg_match 参数顺序错误。首先应该是正则表达式。

所以改变:

preg_match($source_html, $rule, $matches);

到:

preg_match($rule, $source_html, $matches);

【讨论】:

  • 谢谢!好眼力! ...我希望 IDE 能抓住这一点。
【解决方案2】:

我认为您应该尝试将 $rule 作为第一个参数传递:

preg_match($rule, $source_html, $matches);

详情请参考PHP手册:http://php.net/manual/en/function.preg-match.php

【讨论】:

    【解决方案3】:

    必须像这样使用参数(来自 PHP 文档):

    int preg_match ( 字符串 $pattern , 字符串 $subject [, 数组 &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

    所以你需要这样做:

    preg_match($rule, $source_html, $matches);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多