$html"; $dom = new DOMDocument(); $dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $xpath = new DOMXPath($dom); // Limpiar atributos problemáticos primero foreach ($xpath->query('//*[@data-image-description or @data-email-share-n]') as $node) { $node->removeAttribute('data-image-description'); $node->removeAttribute('data-email-share-n'); } // Eliminar todos los atributos excepto los deseados foreach ($xpath->query('//@*') as $attribute) { $node = $attribute->ownerElement; $tag = strtolower($node->nodeName); $attrName = strtolower($attribute->nodeName); $allowedAttrs = [ 'a' => ['href', 'target', 'title', 'rel'], 'img' => ['src', 'alt', 'srcset', 'sizes', 'width', 'height'], 'iframe' => ['src', 'width', 'height', 'allow', 'frameborder', 'allowfullscreen', 'loading'], 'video' => ['src', 'width', 'height', 'controls'], 'source' => ['src', 'type'], ]; if (!isset($allowedAttrs[$tag]) || !in_array($attrName, $allowedAttrs[$tag])) { $node->removeAttributeNode($attribute); } } // Obtener solo el contenido dentro del body $body = $dom->getElementsByTagName('body')->item(0); $cleaned_html = ''; foreach ($body->childNodes as $child) { $cleaned_html .= $dom->saveHTML($child); } libxml_clear_errors(); return $cleaned_html; } public static function remove_css($html) { $html = preg_replace('/]*rel=["\']stylesheet["\'][^>]*>/i', '', $html); $html = preg_replace('/]*>(.*?)<\/style>/is', '', $html); $html = preg_replace('/\s*style=["\'][^"\']*["\']/i', '', $html); return $html; } public static function remove_scripts($html) { $html = preg_replace('/)<[^<]*)*<\/script>/i', '', $html); $html = preg_replace('/\s*on\w+="[^"]*"/i', '', $html); $html = preg_replace("/\s*on\w+='[^']*'/i", '', $html); $html = preg_replace('/\s*on\w+=\w+/i', '', $html); return $html; } public static function remove_buttons($html) { $html = preg_replace('/]*>(.*?)<\/button>/is', '', $html); $html = preg_replace('/]*(type=["\']?(button|submit|checkbox)["\']?)[^>]*>/i', '', $html); return $html; } }