代码之家  ›  专栏  ›  技术社区  ›  Spoike Otávio Décio

在PHP中匹配HTML正文内容的regex

  •  5
  • Spoike Otávio Décio  · 技术社区  · 15 年前

    我需要一个PHP中的regex来匹配元素标记之间的内容,例如 <body> </body> 与Perl兼容 preg_match .

    到目前为止,我尝试了:

    // $content is a string with html content
    
    preg_match("/<body(.|\r\n)*\/body>/", $content, $matches);
    
    print_r($matches);
    

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

    2 回复  |  直到 15 年前
        1
  •  9
  •   Wookai    15 年前

    您只需添加 s 使点匹配所有字符(包括新行)的修饰符:

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

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

        2
  •  0
  •   chub    15 年前

    PerlRegExp默认匹配一行

    必须指定要通过在最后一个搜索后添加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