walter
walter

Reputation: 111

Reg expression to remove empty Tags (any of them)?

I like to remove any empty html tag which is empty or containing spaces.

something like to get:

$string = "<b>text</b><b><span> </span></b><p>  <br/></p><b></b><font size='4'></font>";

to:

$string ="<b>text</b>=;

Upvotes: 0

Views: 1979

Answers (3)

Gordon
Gordon

Reputation: 316989

Here is an approach with DOM:

// init the document
$dom = new DOMDocument;
$dom->loadHTML($string);

// fetch all the wanted nodes
$xp = new DOMXPath($dom);
foreach($xp->query('//*[not(node()) or normalize-space() = ""]') as $node) {
    $node->parentNode->removeChild($node);
}

// output the cleaned markup
echo $dom->saveXml(
    $dom->getElementsByTagName('body')->item(0)
);

This would output something like

<body><b>text</b></body>

XML documents require a root element, so there is no way to omit that. You can str_replace it though. The above can handle broken HTML.

If you want to selectively remove specific nodes, adjust the XPath query.

Also see

Upvotes: 3

akond
akond

Reputation: 16035

function stripEmptyTags ($result)
{
    $regexps = array (
    '~<(\w+)\b[^\>]*>\s*</\\1>~',
    '~<\w+\s*/>~'
    );

    do
    {
        $string = $result;
        $result = preg_replace ($regexps, '', $string);
    }
    while ($result != $string);

    return $result;
}


$string = "<b>text</b><b><span> </span></b><p>  <br/></p><b></b><font size='4'></font>";
echo stripEmptyTags ($string);

Upvotes: 1

Mihai Toader
Mihai Toader

Reputation: 12243

You will need to run the code multiple times in order to do this only with regular expressions.

the regex that does this is:

/<(?:(\w+)(?: [^>]*)?`> *<\/$1>)|(?:<\w+(?: [^>]*)?\/>)/g

But for example on your string you have to run it at least twice. Once it will remove the <br/> and the second time will remove the remaining <p> </p>.

Upvotes: 0

Related Questions