【问题标题】:Regex to match content of HTML body in PHP正则表达式匹配 PHP 中 HTML 正文的内容
【发布时间】:2010-11-18 21:28:19
【问题描述】:

我需要一个 php 中的正则表达式来匹配元素标签之间的内容,例如<body></body> 与 perl 兼容 preg_match

到目前为止,我尝试过:

// $content is a string with html content

preg_match("/<body(.|\r\n)*\/body>/", $content, $matches);

print_r($matches);

…但打印输出是一个空数组。

【问题讨论】:

    标签: php regex multiline matching


    【解决方案1】:

    您只需添加 s 修饰符即可让点匹配所有字符,包括新行:

    preg_match("/<body.*\/body>/s", $content, $matches);
    

    如文档中所述:http://nl2.php.net/manual/en/reference.pcre.pattern.modifiers.php

    【讨论】:

      【解决方案2】:

      perl 正则表达式默认匹配一行

      您必须通过在最后一个 / 之后添加 s 或 m 来指定要进行多行搜索

      例如:

      $> perl -e 'print $1 if "bla\nbla\n<body>\nfirst line\n second line\n</body>\nbla" =~ /^.*<body>(.*)<\/body>.*$/s'
      

      见: http://www.perl.com/pub/a/2003/06/06/regexps.html

      【讨论】:

      • 设置 -m 标志是不够的,因为它只会改变 ^ 和 $ 运算符的行为。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多