【问题标题】:How to remove empty html tags (which contain whitespaces and/or their html codes)如何删除空的 html 标签(包含空格和/或其 html 代码)
【发布时间】:2015-09-01 03:31:14
【问题描述】:

需要一个用于 preg_replace 的正则表达式。

“另一个问题”中没有回答此问题,因为并非我要删除的所有标签都不为空。

我不仅要从 HTML 结构中删除空标签,还要删除包含换行符、空格和/或其 html 代码的标签。

可能的代码是:


             

在删除匹配标签之前:

<div> 
  <h1>This is a html structure.</h1> 
  <p>This is not empty.</p> 
  <p></p> 
  <p><br /></p>
  <p> <br /> &;thinsp;</p>
  <p>&nbsp;</p> 
  <p> &nbsp; </p> 
</div>

删除匹配标签后:

<div> 
  <h1>This is a html structure.</h1> 
  <p>This is not empty.</p> 
</div>

【问题讨论】:

标签: php html regex preg-replace


【解决方案1】:

您可以使用以下内容:

<([^>\s]+)[^>]*>(?:\s*(?:<br \/>|&nbsp;|&thinsp;|&ensp;|&emsp;|&#8201;|&#8194;|&#8195;)\s*)*<\/\1>

并替换为''(空字符串)

DEMO

注意:这也适用于带有属性的空 html 标签。

【讨论】:

  • 您好,我更新了您的测试并在标签内添加空格时失败。这是error 的链接,而另一个link 与调整有关。你刚刚在关闭捕获组之前错过了这个|&amp;#8195;)\s*|\s*)
  • 这是一个很好的答案,但应更新为 this 以处理这两种情况:&lt;br&gt;&lt;br/&gt;
  • 排除iframe、canvas等标签preg_replace('~&lt;((?!iframe|canvas)\w+)[^&gt;]*&gt;(?:\s*(?:&lt;br \/&gt;|&amp;nbsp;|&amp;thinsp;|&amp;ensp;|&amp;emsp;|&amp;#8201;|&amp;#8194;|&amp;#8195;)\s*)*&lt;\/\1&gt;~iu', "", $html)
【解决方案2】:

使用tidy它使用以下函数:

function cleaning($string, $tidyConfig = null) {
    $out = array ();
    $config = array (
            'indent' => true,
            'show-body-only' => false,
            'clean' => true,
            'output-xhtml' => true,
            'preserve-entities' => true 
    );
    if ($tidyConfig == null) {
        $tidyConfig = &$config;
    }
    $tidy = new tidy ();
    $out ['full'] = $tidy->repairString ( $string, $tidyConfig, 'UTF8' );
    unset ( $tidy );
    unset ( $tidyConfig );
    $out ['body'] = preg_replace ( "/.*<body[^>]*>|<\/body>.*/si", "", $out ['full'] );
    $out ['style'] = '<style type="text/css">' . preg_replace ( "/.*<style[^>]*>|<\/style>.*/si", "", $out ['full'] ) . '</style>';
    return ($out);
}

【讨论】:

    【解决方案3】:

    我不太擅长,但是,试试这个

    \<.*\>\s*\&.*sp;\s*\<\/.*\>|\<.*\>\s*\<\s*br\s*\/\>\s*\&.*sp;\s*\<\/.*\>|\<.*\>\s*\&.*sp;\s*\<\s*br\s*\/\>\<\/.*\>
    

    基本匹配

    • 标签中包含 HTML 空间元素或
    • 在 HTML 空间元素之前出现中断的标签
    • 在 HTML 空间元素之后出现中断的标签

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-20
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 2016-07-05
      • 1970-01-01
      相关资源
      最近更新 更多