doz59484 2014-11-11 19:04
浏览 172
已采纳

Simple_html_dom:如何删除具有属性值的所有元素,第一个除外?

A few elements in my HTML page have the same value for the class attribute. I want to remove all of them (elements) except the first one.

I wrote the following SSCCE. So the question is

There are two loops being executed, the first one changes the attribute value for the first element and breaks the loop, and the second one then removes the elements with that attribute value.

So is there a shorter, less costly (in terms of memory, speed etc.) or more straightforward way to do this? May be can be done in a single loop or something like that? I feel I am making it unnecessarily long.

<?php

require_once("E:\\simple_html_dom.php");

$haystack = '<div>
    <div class="removable" style="background-color:pink; width:100%; height:50px;">aa</div>
    <div style="background-color:brown; width:100%; height:50px;">ss</div>
    <div class="removable" style="background-color:grey; width:100%; height:50px;">dd</div>
    <div class="removable" style="background-color:green; width:100%; height:50px;">gg</div>
    <div style="background-color:blue; width:100%; height:50px;">hh</div>
    <div class="removable" style="background-color:purple; width:100%; height:50px;">jj</div>
</div>';

$html_haystack = str_get_html($haystack);

//echo $html_haystack; //check

foreach ($html_haystack->find('div[class=removable]') as $removable) {
    $removable->class='removable_first';
    //$removable->style='background-color:black; width=100%; height=50px;'; //check
    break;
}

foreach($html_haystack->find('div[class=removable]') as $removable) {
    $removable->outertext= '';
}

$haystack = $html_haystack->save();

echo $haystack;
  • 写回答

2条回答 默认 最新

  • dougouqin0763 2014-11-11 20:27
    关注

    Find function returns an array, so the first element has index 0. No need then to use the 1st loop !

    // Get all nodes
    $array = $html_haystack->find('div[class=removable]');
    
    // Edit the 1st => maybe you won't need this line if you're doing so only to skip the 1st node
    $array[0]->class='removable_first';
    
    // Remove the 1st from the array
    unset($array[0]);
    
    // Loop through the other nodes
    foreach($array as $removable) {
        $removable->outertext= '';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。