Strip all HTML tags, except allowed
There is a common pattern in text processing where you need to sanitize input by removing dangerous or unnecessary markup while preserving semantic structure. You might find yourself needing to strip out everything but specific elements like paragraphs, bold text, links, and lists. While standard regex solutions exist for removing a single tag type or even a list of tags, finding a clean approach in PHP that targets "all except" a specific set can be tricky without diving into complex regular expressions.
The core challenge lies in the nature of HTML parsing. Regular expressions are linear tools designed to match patterns sequentially. They struggle with nested structures and recursive logic inherent in markup languages. Attempting to write a regex that says "remove everything that isn't a <p>, <b>, or <a>" often leads to catastrophic backtracking or requires an impractically complex pattern that breaks on edge cases like self-closing tags or nested elements.
A more robust solution involves using a dedicated parser rather than raw string manipulation. In the PHP ecosystem, the DOMDocument class provides a DOMParser interface that allows you to traverse the document tree. This method lets you programmatically identify nodes and decide which ones to keep based on their tag names.
Here is a practical implementation using DOMDocument. First, you load the HTML string into the document object:
$html = '<p>Hello <b>World</b>!</p><span>Bolded<span style="color:red">Text</span></span>';
$dom = new DOMDocument();
// Suppress warnings for malformed HTML often found in user input
libxml_use_internal_errors(true);
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
// Remove all nodes that are NOT in the allowed list
$allowedTags = ['p', 'b', 'i', 'u', 'a', 'ul', 'ol', 'li'];
foreach ($dom->getElementsByTagName('*') as $node) {
if (!in_array($node->tagName, $allowedTags)) {
$node->parentNode->removeChild($node);
}
}
$output = $dom->saveHTML();
This approach iterates through every element in the document. If a node's tag name is not present in your $allowedTags array, it removes that node from its parent. This effectively strips out spans, divs, and other unwanted containers while leaving the allowed semantic tags intact.
One critical detail when working with DOMDocument is handling malformed HTML or missing DOCTYPE declarations. By default, PHP's DOM parser might attempt to fix these issues automatically, which can alter your document structure unexpectedly. Using the flags LIBXML_HTML_NOIMPLIED and LIBXML_HTML_NODEFDTD ensures that the parser treats the input exactly as provided without injecting default <html> or <body> tags unless they are explicitly present in the source string.
Another consideration is handling attributes within the allowed tags. The code above preserves all attributes on the retained elements. If you need to sanitize attributes (removing onclick handlers, for instance), you must extend the logic to check the attribute list alongside the tag name. This adds a layer of security but requires more careful implementation to avoid breaking valid data.
While regex might seem tempting for its brevity, relying on it for this specific "inverse" filtering task often results in brittle code that fails on nested structures or complex HTML fragments. Using the DOM parser trades a few lines of extra code for significant reliability and maintainability. If you are building a content pipeline where data integrity is paramount, this structural approach is the industry standard.
For those working within the Laravel framework, similar logic can be applied using native PHP classes, as there isn't a built-in helper specifically for "keep only" tag filtering out of the box. However, third-party packages or custom service providers often implement DOM-based sanitizers to handle these specific requirements. If you need a reusable component in your project architecture, encapsulating this logic in a dedicated class makes it easily testable and configurable via an array of allowed tags.