How to remove empty paragraph tags from string?

This gets rid of all empty p tags, even if they contain spaces or &nbps; inside.

$str = "<p>  </p><p> &nbsp; </p><p>&nbsp</p><p>Sample Text</p>";

echo preg_replace("/<p[^>]*>(?:\s|&nbsp;)*<\/p>/", '', $str);

This only echoes <p>Sample Text</p>


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( '&nbsp;', ' ', $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">&nbsp;</span>
            </p>
        </div>
    </p>
    ';

echo teaser( $html );

?>

The function returns:

<p>Hello!

</p>

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>
?>

Tags:

Php