【问题标题】:How can I extract or cut html contents of inside <div id="mainContent" ......> ........ </div>? The html source is not correctly formatted如何提取或剪切 <div id="mainContent" ......> ........ </div> 内部的 html 内容? html 源的格式不正确
【发布时间】:2012-05-03 20:17:46
【问题描述】:
<html>
    <head><title>bla bla</title></head>
    <body>
    <div id="mainContent" xmlns:h="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml">
        bla bla .....
    </div>
    </body>
</html>

我需要提取那个除法。我如何使用 PHP 5 来做到这一点?

html 源代码的格式不正确。有一些未定义的属性。

【问题讨论】:

标签: php regex parsing html-parsing


【解决方案1】:

如果您的 HTML 格式不正确,您仍然可以使用 DOMDocument 之类的内容,例如:

$d = new DOMDocument;
$d->loadHTML($htmlstring);

$x = new DomXPath($d);

foreach ($x->query('//div[@id="mainContent"]') as $node) {
    echo $node->nodeValue;
}

或者,只需在 HTML 前加上 &lt;!DOCTYPE html&gt; 前缀,以便您可以正常使用 getElementById

【讨论】:

    【解决方案2】:

    /&lt;div id=\"mainContent\".*?&lt;/div&gt;/gs

    http://regexr.com?30o0l 如果你想捕获从 div 开始标签到结束标签的所有内容。

    【讨论】:

    • 这将匹配任何平铺 last 结束标签。它只适用于这个非常简单的例子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    相关资源
    最近更新 更多