簡體   English   中英

Simple_html_dom:如何刪除除第一個屬性值外的所有具有屬性值的元素?

[英]Simple_html_dom: how to remove all elements with an attribute value, except the first one?

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;

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= '';
}
$html->find('.removable', 0)->class = 'removable_first';

foreach($html->find('.removable') as $removable){
  $removable->outertext = '';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM