I'm using PHP's DOMDocument to remove divs matching a specific class name. So in my example below, I'm removing any element with the class name of 'remove-me'.
$content = '<div class="keep-me">Keep this div</div><div class="remove-me">Remove this div</div>';
$badClasses = array('remove-me');
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($content);
$xPath = new DOMXpath($dom);
foreach($badClasses as $badClass){
$domNodeList = $nodes = $xPath->query('//*[contains(@class, "'.$badClass.'")]');
$domElemsToRemove = array();
foreach ( $domNodeList as $domElement ) {
// ...do stuff with $domElement...
$domElemsToRemove[] = $domElement;
}
foreach( $domElemsToRemove as $domElement ){
$domElement->parentNode->removeChild($domElement);
}
}
$content = $dom->saveHTML();
Is there any way I can keep all the removed element, convert them to a HTML string so that I can echo the html elsewhere on my page?