3v4l.org

run code in 300+ PHP versions simultaneously
<?php $html = <<<'HTML' <article> <p rel="#" src="#">aaaaaa</p> <p href="#" bla="#" bla2="#">bbbbbb</p> </article> HTML; $dom = new DOMDocument; @$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $xpath = new DomXPath($dom); $elements = $xpath->query('//article/*'); $allowedAttributes = ['src', 'href']; foreach($elements as $element) { for( $i = $element->attributes->length; --$i >= 0; ) { if( ! in_array( $element->attributes->item($i)->name, $allowedAttributes ) ) { $element->removeAttribute($element->attributes->item($i)->name); } } } echo $dom->saveHTML();

preferences:
201.84 ms | 404 KiB | 5 Q