Removing Empty Paragraph Tags After Stripping HTML
When processing content for a feed, API response, or template snippet, you often need to sanitize HTML while preserving specific formatting elements like bold text or lists. A common pattern involves using strip_tags() to remove unwanted markup while keeping allowed tags intact. However, this approach frequently leaves behind orphaned empty paragraph tagsâinstances where an image or script was removed, but the surrounding <p> wrapper remains.
Consider a scenario where you have content structured like this:
<p>Some text here.</p>
<p><img src="path/to/image.jpg" alt="An image"></p>
<p>More text after the image.</p>
If your sanitization logic allows <p> tags but strips <img> tags to prevent broken references or XSS vulnerabilities, the result is:
<p>Some text here.</p>
<p></p>
<p>More text after the image.</p>
The second paragraph is now empty. While visually harmless in a browser, these artifacts can clutter data exports, break strict HTML validators, or cause layout issues if CSS relies on block-level elements for spacing.
Why strip_tags() Leaves Orphans
The core issue lies in how strip_tags() operates. It iterates through the DOM (or string) and removes tags not found in your allowed list. Crucially, it does not automatically collapse adjacent whitespace or merge empty nodes into their neighbors. When an <img> tag is inside a <p>, removing the image leaves the paragraph node itself intact but devoid of children.
To resolve this, you must post-process the cleaned string to identify and remove tags that contain no content (or only whitespace).
The Regex Solution
The most direct way to handle this in PHP is by extending your existing strip_tags() call with a secondary regex replacement. You can target paragraph tags specifically if they are empty:
$content = strip_tags($content, '<p><a>'); // Keep p and a for now
// Remove empty paragraph tags that contain only whitespace or nothing
$content = preg_replace('/<p\b[^>]*>(?:(?!<[a-z].*>).)*<\/p>/i', '', $content);
However, regex logic can get messy with nested tags. A more robust approach involves a two-step process: first strip the unwanted tags entirely, then collapse empty paragraphs into their surrounding text or remove them if they are truly isolated.
Here is a cleaner implementation strategy that handles the specific case of removing empty <p> tags after stripping images and other media:
function cleanTeaser($content) {
// 1. Initial strip to keep only allowed structural tags
$allowed = '<p><a><ul><li><i><em><strong>';
$content = strip_tags($content, $allowed);
// 2. Remove empty paragraphs.
// This regex matches <p>...</p> where ... is either null or only whitespace/newlines
$content = preg_replace('/<p\b\s*>(?:(?!<[a-z].*>).)*?<\s*\/p>/i', '', $content);
// 3. Optional: Collapse multiple consecutive newlines created by removal
$content = preg_replace('/\n{3,}/', "\n\n", $content);
return trim($content);
}
A Better Approach: Remove Tags First
Often, the cleanest solution is to avoid keeping <p> tags in your allowed list until you have finished cleaning the content. If your goal is to produce plain text for a teaser, there is no need to preserve paragraph breaks during the intermediate strip_tags() step.
Instead, strip all tags first, then handle the whitespace. This prevents the creation of empty nodes entirely:
function cleanTeaser($content) {
// Strip ALL tags initially
$cleanContent = strip_tags($content);
// Now you have plain text. You can safely trim and normalize spaces.
// The "empty paragraph" problem never exists because no <p> tags were kept.
$cleanContent = preg_replace('/\s+/', ' ', $cleanContent); // Normalize whitespace
$cleanContent = trim($cleanContent);
return $cleanContent;
}
If you strictly require preserving lists (<ul>, <li>) or bold text (<strong>), you should only allow those tags in strip_tags(). Since <p> is a block-level container that often wraps inline elements like images, removing it alongside the image usually yields better results than trying to surgically remove empty instances later.
Trade-offs and Limitations
When deciding whether to keep <p> tags or strip them all, consider your downstream requirements. If you are generating HTML for a blog post where paragraph breaks are semantically important, stripping them entirely destroys that structure. In that case, the regex approach is necessary but requires careful testing against edge cases, such as paragraphs containing only whitespace or paragraphs with trailing non-stripped tags.
Another pitfall is relying on apply_filters('the_content', ...) before sanitization without accounting for how those filters might inject additional HTML that needs stripping. Ensure your sanitization step happens after all necessary WordPress filters have run, but before the content is outputted to the user or stored in a cache.
Finally, remember that strip_tags() is a string manipulation function, not a DOM parser. It does not understand hierarchy. If you need complex restructuring (e.g., moving text from an empty paragraph into the previous one), simple regex might suffice for basic cases, but a library like DOMDocument offers more precise control over node removal and merging.