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

后端 未结 3 967
醉酒成梦
醉酒成梦 2020-12-18 17:21

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

something like to get:

$string = \"text&         


        
相关标签:
3条回答
  • 2020-12-18 17:29
    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);
    
    0 讨论(0)
  • 2020-12-18 17:33

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

    0 讨论(0)
  • 2020-12-18 17:35

    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
    0 讨论(0)
提交回复
热议问题