fork download
  1. <?
  2.  
  3. $xhtml = '<p style="width: 250px;">This is some text<div class="button">This is the button</div><br><img src="waves.jpg" width="150" height="200" /></p><p><b>Title</b><br>Here is some more text and <a href="#" target="_blank">this is a link</a></p>';
  4.  
  5. $dom = new DOMDocument();
  6. $dom->loadHTML($xhtml);
  7.  
  8. function clean($element, $allowed, $stripped, $prefix = ''){
  9. if(!is_array($allowed) || ! is_array($stripped)) return;
  10. if(!$element)return;
  11. $toDelete = array();
  12. foreach($element->childNodes as $child){
  13. if(!isset($child->tagName))continue;
  14. $n = $child->tagName;
  15. if ($n && !in_array($n, $allowed) && !in_array($n, $stripped)){
  16. $toDelete[] = $child;
  17. continue;
  18. }
  19. if($n && in_array($n, $stripped)){
  20. $attr = array();
  21. foreach($child->attributes as $a)
  22. $attr[] = $a->nodeName;
  23. foreach($attr as $a)
  24. $child->removeAttribute($a);
  25. }
  26. clean($child, $allowed, $stripped, $prefix.' ');
  27. }
  28. foreach ($toDelete as $del)
  29. $element->removeChild($del);
  30. }
  31. $body = $dom->getElementsByTagName('body')->item(0);
  32. clean($body, array('img', 'a'), array('p', 'br', 'b'));
  33. echo preg_replace('#^.*?<body>(.*?)</body>.*$#s', '$1', $dom->saveHTML($body));
Success #stdin #stdout #stderr 0.01s 20520KB
stdin
Standard input is empty
stdout
<p>This is some text</p>
<br><img src="waves.jpg" width="150" height="200"><p><b>Title</b><br>Here is some more text and <a href="#" target="_blank">this is a link</a></p>
stderr
PHP Warning:  DOMDocument::loadHTML(): Unexpected end tag : p in Entity, line: 1 in /home/xmcpo7/prog.php on line 6