首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Simple_html_dom:如何删除除了第一个属性值之外的所有元素?

Simple_html_dom:如何删除除了第一个属性值之外的所有元素?
EN

Stack Overflow用户
提问于 2014-11-11 19:04:54
回答 2查看 879关注 0票数 0

我的HTML页面中有几个元素对class属性具有相同的值。除了第一个元素之外,我想删除所有的元素。

我编写了以下SSCCE。所以问题是

有两个循环正在执行,第一个循环更改第一个元素的属性值并中断循环,第二个循环则删除带有该属性值的元素。

还有更短、更便宜的(内存、速度等)吗?或者更直接的方法?可以在一个循环或类似的事情中完成吗?我觉得我做的太长了。

代码语言:javascript
复制
<?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;
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-11-11 20:27:12

Find函数返回一个数组,因此第一个元素具有索引0。没有必要使用第一个循环!

代码语言:javascript
复制
// 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= '';
}
票数 2
EN

Stack Overflow用户

发布于 2014-11-11 21:21:33

代码语言:javascript
复制
$html->find('.removable', 0)->class = 'removable_first';

foreach($html->find('.removable') as $removable){
  $removable->outertext = '';
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26872515

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档