我的HTML页面中有几个元素对class属性具有相同的值。除了第一个元素之外,我想删除所有的元素。
我编写了以下SSCCE。所以问题是
有两个循环正在执行,第一个循环更改第一个元素的属性值并中断循环,第二个循环则删除带有该属性值的元素。
还有更短、更便宜的(内存、速度等)吗?或者更直接的方法?可以在一个循环或类似的事情中完成吗?我觉得我做的太长了。
<?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;发布于 2014-11-11 20:27:12
Find函数返回一个数组,因此第一个元素具有索引0。没有必要使用第一个循环!
// 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= '';
}发布于 2014-11-11 21:21:33
$html->find('.removable', 0)->class = 'removable_first';
foreach($html->find('.removable') as $removable){
$removable->outertext = '';
}https://stackoverflow.com/questions/26872515
复制相似问题