正则表达式匹配PHP中HTML体的内容

Spo*_*ike 5 php regex multiline matching

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

到目前为止,我试过:

// $content is a string with html content

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

print_r($matches);
Run Code Online (Sandbox Code Playgroud)

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

Woo*_*kai 9

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

preg_match("/<body.*\/body>/s", $content, $matches);
Run Code Online (Sandbox Code Playgroud)

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