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

解析HTML并获取所有h3之后的h2之前的下一个h2使用PHP,第1张

概述我期待在文章中找到第一个h2.一旦找到,找到所有h3,直到找到下一个h2.冲洗并重复,直到找到所有标题和副标题. 在您立即将此问题标记或关闭为重复解析问题之前,请注意问题标题,因为这与基本节点检索无关.我已经把那部分搞定了. 我使用DOMDocument来解析使用DOMDocument::loadHTML(),DOMDocument::getElementsByTagName()和DOMDocum 我期待在文章中找到第一个h2.一旦找到,找到所有h3,直到找到下一个h2.冲洗并重复,直到找到所有标题和副标题.

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

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

我的代码如下:

$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的兄弟,直到遇到下一个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);           }    }}
总结

以上是内存溢出为你收集整理的解析HTML并获取所有h3之后的h2之前的下一个h2使用PHP全部内容,希望文章能够帮你解决解析HTML并获取所有h3之后的h2之前的下一个h2使用PHP所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1042880.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存