Несколько элементов на моей странице HTML имеют одинаковое значение для атрибута класса. Я хочу удалить все из них (элементы), кроме первого.
Я написал следующий 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
. Нет необходимости использовать 1-й цикл!
// 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 = '';
}