How to remove empty paragraph tags from string?
Solution 1:
use this regex to remove empty paragraph
/<p[^>]*><\\/p[^>]*>/
example
<?php
$html = "abc<p></p><p>dd</p><b>non-empty</b>";
$pattern = "/<p[^>]*><\\/p[^>]*>/";
//$pattern = "/<[^\/>]*>([\s]?)*<\/[^>]*>/"; use this pattern to remove any empty tag
echo preg_replace($pattern, '', $html);
// output
//abc<p>dd</p><b>non-empty</b>
?>
Solution 2:
This gets rid of all empty p
tags, even if they contain spaces
or &nbps;
inside.
$str = "<p> </p><p> </p><p> </p><p>Sample Text</p>";
echo preg_replace("/<p[^>]*>(?:\s| )*<\/p>/", '', $str);
This only echoes <p>Sample Text</p>
Solution 3:
This function remove empty elements and then, other empty elements, created from previous removed elements. (The example string contains spaces, tabs and carriage returns.)
function teaser( $html ) {
$html = str_replace( ' ', ' ', $html );
do {
$tmp = $html;
$html = preg_replace(
'#<([^ >]+)[^>]*>[[:space:]]*</\1>#', '', $html );
} while ( $html !== $tmp );
return $html;
}
Having the following example:
<?php
$html = '
<p>Hello!
<div class="foo">
<p id="nobody">
<span src="ok"> </span>
</p>
</div>
</p>
';
echo teaser( $html );
?>
The function returns:
<p>Hello!
</p>
Solution 4:
Use str_replace to remove empty <p></p>
tags.
$content = str_replace("<p></p>","",$content);
Anything more advanced will need regular expressions.