Preg_match_all - 标记后的第2个段落

问题描述 投票:2回答:1

在变量$url中,具有网站的内容

下面的div里面有页面的所有主要内容

<div id="mw-content-text" lang="pt" dir="ltr" class="mw-content-ltr">

我想找到有“História”的<H2>

<h2><span id="Hist.C3.B3ria"></span><span class="mw-headline" id="História">História</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Adamantina&amp;veaction=edit&amp;section=1" class="mw-editsection-visualeditor" title="Editar secção: História">editar</a><span class="mw-editsection-divider"> | </span><a href="/w/index.php?title=Adamantina&amp;action=edit&amp;section=1" title="Editar secção: História">editar código-fonte</a><span class="mw-editsection-bracket">]</span></span></h2>

关闭<h2>的开放</h2>标签之间有很多代码,因为有可能看到上面

但是我需要在包含“História”的<p>标签之后只获得前两段</h2>

preg_match_all('/<h2>(.+)</h2>/s', $url, $content);

如何输入必须具有“História”的正则表达式,以及如何仅在</h2>标记之后过滤前两个段落?

php regex preg-match-all
1个回答
2
投票

您甚至不应该尝试使用正则表达式执行此操作。您正在解析HTML文档,正确的工具是DOM解析器。 PHP有DOMDocumentDOMXPath类可以使用,所以不要三思而后行:

$document = new DOMDocument();
$document->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
$domxpath = new DOMXPath($document);
$paragraphs = $domxpath->query('
    //h2[*[
            contains(text(), "História")
          ]
        ]
    /following-sibling::p[
            position() < 3
        ]
');
var_dump($paragraphs);

PHP live demo

你在$paragraphs有两个以下的兄弟段落。你需要迭代它们来做任何你想做的事情。

© www.soinside.com 2019 - 2024. All rights reserved.