2010-12-19 40 views
0

从字符串中删除空html标记的最快方法是什么?使用PHP检查和删除空标记

我已经设定这样的事情来检测空锚标签:

     $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并在那里检查会更快吗?

回答

1

Regular expressions are not the right tool for parsing HTML.

作为一个非具体的答案,我强烈建议使用DOM解析库来实现这一目标。仅举几例陷阱,这将使正则表达式的噩梦:

  1. 你可能赶上<a></a>标签,但你会赶上<a />标签?
  2. 以下p标签为空吗?:<p><a></a></p>如果是这样,您的代码是否会捕获它?如果没有,那么在你有足够的信心让他们全部抓住之前,你需要多少次传球?
  3. 你会抓住没有正确关闭的标签吗?
  4. 你会抓住重叠的标签吗?