PHP DOMDocument – remove span by style attributes

  dom, domdocument, php

I’m trying to remove span tags with a specific style (preserving the text) but don’t understand why the result is putting span text inside the first span in this example?

    $curr_notes = '<span style="color: rgb(226, 80, 65);"><br></span><span style="color: rgb(0, 0, 0);">TEXT 1</span><br><span style="color: rgb(0, 0, 0);">TEXT2</span>';
    $pattern    = '//span[@style="color: rgb(0, 0, 0);"]';

    $dom = new DOMDocument();
    $dom->loadHTML($curr_notes, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

    $xpath = new DOMXPath($dom);

    foreach ($xpath->query($pattern) as $span) {

        while ($span->hasChildNodes()) {
            $child = $span->removeChild($span->firstChild);
            $span->parentNode->insertBefore($child, $span);
        }

        $span->parentNode->removeChild($span);
    }

    // Get the final HTML with span tags stripped
    $clean_notes = $dom->saveHTML();

    echo $clean_notes;
    // <span style="color: rgb(226, 80, 65);"><br>TEXT 1<br>TEXT2</span>

    // am expecting
    // <span style="color: rgb(226, 80, 65);"><br></span>TEXT 1<br>TEXT2

Source: Ask PHP

LEAVE A COMMENT