使用PHP匹配html <body>标记之间的所有内容

Rol*_*and 5 php regex html-parsing

我有一个脚本,在一个名为$ content的变量中返回以下内容

<body>
<p><span class=\"c-sc\">dgdfgdf</span></p>
</body>
Run Code Online (Sandbox Code Playgroud)

但是我需要在body标签中放置一个名为matches的数组

我执行以下操作来匹配body标签之间的内容

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

但$ mathces数组是空的,我怎么能让它返回body标签内的所有内容

sou*_*rge 12

不要尝试使用正则表达式处理html!改为使用PHP的内置解析器:

$dom = new DOMDocument;
$dom->loadHTML($string);
$bodies = $dom->getElementsByTagName('body');
assert($bodies->length === 1);
$body = $bodies->item(0);
for ($i = 0; $i < $body->children->length; $i++) {
    $body->remove($body->children->item($i));
}
$string = $dom->saveHTML();
Run Code Online (Sandbox Code Playgroud)


Mar*_*ers 10

您不应该使用正则表达式来解析HTML.

在这种情况下,您的特殊问题是需要添加DOTALL修改器以使点与换行符匹配.

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

但严重的是,请改用HTML解析器.上面的正则表达式有很多种方法可以打破.