dongsu3664 2016-02-02 09:52
浏览 100
已采纳

在HTML文档中查找具有特定类的所有div

Using PHP, how can I extract all <div class="this"> even though it appears on different hierarchical levels in a HTML document?

<h3>Hello</h3>
<p>World</p>
<div class="this">
    (lots of random markup, including other divs)
</div>
<div class="this">
    (more random markup, including other divs)
</div>
<div class="inside">
    <div class="this">
        (even more random markup, including other divs)
    </div>
</div>
<p>Bye.</p>

If it's not possible to achieve with regular expressions, does PHP have a built-in library that makes it easy to do something like this (pseudo-code)?

$result = find_all($html, "div", "this");

Desired result:

$result = array(
'<div class="this">
    (lots of random markup, including other divs)
</div>',
'<div class="this">
    (more random markup, including other divs)
</div>',
'<div class="this">
    (even more random markup, including other divs)
</div>',
);
  • 写回答

3条回答 默认 最新

  • duanbi8529 2016-02-02 11:24
    关注

    You can use PHP Simple HTML DOM Parser for your work , your code is something like below lines :

        <?php
    include_once "simple_html_dom.php";
    
    $html = str_get_html('<h3>Hello</h3><p>World</p><div class="this"> (lots of random markup, including other divs)</div><div class="this"> (more random markup, including other divs)</div><div class="inside"> <div class="this"> (even more random markup, including other divs) </div></div><p>Bye.</p>');
    
    $divs = $html->find('div.this');
    $ans=array();
    foreach($divs as $div){
    $ans[]=$div->outertext;
    }
    
    print_r($ans);
    
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!