I\'m using DOM to parse string. I need function that strips span tags and its contents. For example, if I have:
This is some text that contains photo.
@ile - I've had that problem - it's because the index of the foreach iterator happily keeps incrementing, while calling removeChild() on the DOM also seems to remove the nodes from the DomNodeList ($spans). So for every span you remove, the nodelist shrinks one element and then gets its foreach counter incremented by one. Net result: it skips one span.
I'm sure there is a more elegant way, but this is how I did it - I moved the references from the DomNodeList to a second array, where they would not be removed by the removeChild() operation.
foreach($spans as $span) {
$nodes[] = $span;
}
foreach($nodes as $span) {
$span->parentNode->removeChild($span);
}
Try removing the spans directly from the DOM tree.
$dom = new DOMDocument();
$dom->loadHTML($string);
$dom->preserveWhiteSpace = false;
$elements = $dom->getElementsByTagName('span');
while($span = $elements->item(0)) {
$span->parentNode->removeChild($span);
}
echo $dom->saveHTML();