Remove a specific span tag from HTML while preserving/keeping the inside content using PHP and DOMDocument

remove-span-tags-from-html.php

<?php

$content = '<span style="font-family: helvetica; font-size: 12pt;"><div>asdf</div><span>TWO</span>Business owners are fearful of leading. They would rather follow the leader than embrace a bold move that challenges their confidence. </span>';

$dom = new DOMDocument();
// Use LIBXML for preventing output of doctype, <html>, and <body> tags
$dom->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$xpath = new DOMXPath($dom);

foreach ($xpath->query('//span[@style="font-family: helvetica; font-size: 12pt;"]') as $span) {

    // Move all span tag content to its parent node just before it.
    while ($span->hasChildNodes()) {
        $child = $span->removeChild($span->firstChild);
        $span->parentNode->insertBefore($child, $span);
    }

    // Remove the span tag.
    $span->parentNode->removeChild($span);
}

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

print_r($output);
No comments yet.

Leave a Reply