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> &开发者_StackOverflow中文版lt;br/></p><b></b><font size='4'></font>";
to:
$string ="<b>text</b>=;
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
- How do you parse and process HTML/XML in PHP?
- Locating the node by value containing whitespaces using XPath
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);
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>
.
精彩评论