【问题标题】:Checking and removing empty tags with PHP使用 PHP 检查和删除空标签
【发布时间】:2010-12-19 21:21:00
【问题描述】:

从字符串中删除空 html 标记的最快方法是什么?

我编写了这样的程序来检测空锚标签:

                        $temp = strip_tags($string, "<blockquote><a>");
                        $cmatch = array();
                        if(preg_match_all("~<a.*><\/a>~iU", $temp, $cmatch, PREG_SET_ORDER))
                        {
                            foreach($cmatch as $cm)
                            {
                                foreach($cm as $t) //echo htmlentities($t)."<br />";
                                $temp = trim(str_replace($t, '', $temp));
                            }
                        }

                        if(!empty($temp))
                        {
                            echo '<div class="c" style="margin-top:20px;">';
                            echo $temp;
                            echo '</div>';
                        }
                        //do not output if empty tags (problem with div margin)

必须有可能更有效地做到这一点。将字符串转换为 html DOM 并在那里进行检查会更快吗?

【问题讨论】:

    标签: php html string tags anchor


    【解决方案1】:

    Regular expressions are not the right tool for parsing HTML.

    作为一个非特定的答案,我强烈建议使用 DOM 解析库来完成此操作。举几个让正则表达式成为噩梦的陷阱:

    1. 你可能会捕捉到&lt;a&gt;&lt;/a&gt; 标签,但你会捕捉到&lt;a /&gt; 标签吗?
    2. 下面的p 标签是空的吗?:&lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;/p&gt; 如果是这样,你的代码会捕捉到它吗?如果没有,你需要在绳子上跑多少次才能有足够的信心抓住所有的球?
    3. 你会发现没有正确关闭的标签吗?
    4. 你会发现重叠的标签吗?

    【讨论】:

      猜你喜欢
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 2012-04-11
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      相关资源
      最近更新 更多