Casey

Full-Stack Developer

#php

Strip Attributes from HTML Tags

<?php 

function strip_attributes($html) {
  $dom = new DOMDocument;
  $dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  $xpath = new DOMXPath($dom);
  $nodes = $xpath->query('//@*');
  foreach ($nodes as $node) {             
      if($node->nodeName != "src" && $node->nodeName != "href") {
          $node->parentNode->removeAttribute($node->nodeName);
      }
  }
  return $dom->saveHTML();  
}