php - 使用 PHP 解析 HTML 并在下一个 h2 之前的 h2 之后获取所有 h3

标签 php parsing dom html-parsing domdocument

我正在寻找文章中的第一个 h2。找到后,查找所有 h3,直到找到下一个 h2。冲洗并重复,直到找到所有标题和副标题。

在您立即将此问题标记或关闭为重复解析问题之前,请注意问题标题,因为这与基本节点检索无关。我已经把那部分记下来了。

我正在使用 DOMDocument使用 DOMDocument::loadHTML() 解析 HTML , DOMDocument::getElementsByTagName()DOMDocument::saveHTML()检索文章的重要标题。

我的代码如下:

$matches = array();
$dom = new DOMDocument;
$dom->loadHTML($content);
foreach($dom->getElementsByTagName('h2') as $node) {
    $matches['heading-two'][] = $dom->saveHtml($node);
}
foreach($dom->getElementsByTagName('h3') as $node) {
    $matches['heading-three'][] = $dom->saveHtml($node);
}
if($matches){
    $this->key_points = $matches;
}

这给了我类似这样的输出:

array(
    'heading-two' => array(
        '<h2>Here is the first heading two</h2>',
        '<h2>Here is the SECOND heading two</h2>'
    ),
    'heading-three' => array(
        '<h3>Here is the first h3</h3>',
        '<h3>Here is the second h3</h3>',
        '<h3>Here is the third h3</h3>',
        '<h3>Here is the fourth h3</h3>',
    )
);

我正在寻找更像是:

array(
    '<h2>Here is the first heading two</h2>' => array(
        '<h3>Here is an h3 under the first h2</h3>',
        '<h3>Here is another h3 found under first h2, but after the first h3</h3>'
    ),
    '<h2>Here is the SECOND heading two</h2>' => array(
        '<h3>Here is an h3 under the SECOND h2</h3>',
        '<h3>Here is another h3 found under SECOND h2, but after the first h3</h3>'
    )
);

我并不是在寻找代码完成(如果你觉得这样做会更好地帮助别人——继续吧),但或多或​​少的指导或建议是在正确的方向上完成一个嵌套数组,就像上面那样.

最佳答案

我假设所有标题在 DOM 中都处于同一级别,因此每个 h3 都是 h2 的兄弟。有了这个假设,您可以迭代 h2 的 sibling ,直到遇到下一个 h2:

foreach($dom->getElementsByTagName('h2') as $node) {
    $key = $dom->saveHtml($node);
    $matches[$key] = array();
    while(($node = $node->nextSibling) && $node->nodeName !== 'h2') {
        if($node->nodeName == 'h3') {
            $matches[$key][] = $dom->saveHtml($node);   
        }
    }
}

关于php - 使用 PHP 解析 HTML 并在下一个 h2 之前的 h2 之后获取所有 h3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18156164/

相关文章:

php - mysql计算两个数的区别

php - 在 PHP 中检查日期是否早于 12 小时

jquery - 对日期进行排序并显示不重复的日期

javascript - 当内容来自 Ajax 调用时访问 div 内容时出现问题

javascript - 如何将 jQuery 用于预定义事件?

php - Laravel 中缓慢的 MySQL 查询在其他地方却很快

java - 在java中获取 token 的最佳方式

javascript - 解析不一致的数据

javascript - 通过 DOM 解析获取所有子项和值

php - 安全登录