【问题标题】:How can I grab the entire content inside `<body>` tag with regex?如何使用正则表达式获取 `<body>` 标签内的全部内容?
【发布时间】:2011-10-17 01:23:43
【问题描述】:

如何使用正则表达式获取&lt;body&gt; 标签内的全部内容?

例如,

<html><body><p><a href="#">xx</a></p>

<p><a href="#">xx</a></p></body></html> 

我只想退货,

<p><a href="#">xx</a></p>

<p><a href="#">xx</a></p>

或者还有其他更好的想法吗?也许是 DOM 但我必须使用 saveHTML(); 然后它会返回 doctypebody 标签...

HTML Purifier 使用起来很痛苦,所以我决定不使用它。我认为正则表达式可能是我灾难的下一个最佳选择。

【问题讨论】:

  • 这样的正则表达式对你不起作用&lt;body&gt;(.*)&lt;/body&gt;?
  • @sahid - 不,怎么样,&lt;body class="large-text"&gt; ... &lt;/body&gt;
  • 不要使用正则表达式。 htmlparsing.com/php.html 为您提供了如何使用正确的 HTML 解析器的示例。其实,如果你使用的是simple_html_dom,那么简单到file_get_html('http://www.google.com/')-&gt;plaintext;

标签: php regex html-parsing


【解决方案1】:
preg_match("/<body[^>]*>(.*?)<\/body>/is", $html, $matches);

$matches[1] 将是 body 标签的内容

【讨论】:

【解决方案2】:
preg_match("~<body.*?>(.*?)<\/body>~is", $html, $match);
print_r($match);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多