首页 > 开发 > PHP > 正文

PHP实现补齐关闭的HTML标签

2024-05-04 22:01:42
字体:大 中 小
来源:转载
供稿:网友

本文实例讲述了PHP实现补齐关闭的HTML标签。分享给大家供大家参考,具体如下:

很多时候,在我们做文章截取摘要的时候,如果出现HTML的内容,会出现截取的文章没有结束的HTML标签。这样的情况下就会出现页面样式错乱的问题,这 个时候我们需要的就是把缺少的结束标签加批量加上。在www.php.net官网看到一个比较好处理的一个函数,展示如下:

  1. function CloseTags($html) 
  2.  
  3. { 
  4.  
  5.   // strip fraction of open or close tag from end (e.g. if we take first x characters, we might cut off a tag at the end!) 
  6.  
  7.   $html = preg_replace('/<[^>]*$/','',$html); // ending with fraction of open tag 
  8.  
  9.   // put open tags into an array 
  10.  
  11.   preg_match_all('#<([a-z]+)(?: .*)?(?<!--[/|/ ])-->#iU', $html, $result); 
  12.  
  13.   $opentags = $result[1]; 
  14.  
  15.   // put all closed tags into an array 
  16.  
  17.   preg_match_all('#<!--([a-z]+)-->#iU', $html, $result); 
  18.  
  19.   $closetags = $result[1]; 
  20.  
  21.   $len_opened = count($opentags); 
  22.  
  23.   // if all tags are closed, we can return 
  24.  
  25.   if (count($closetags) == $len_opened) { 
  26.  
  27.    return $html; 
  28.  
  29.   } 
  30.  
  31.   // close tags in reverse order that they were opened 
  32.  
  33.   $opentags = array_reverse($opentags); 
  34.  
  35.   // self closing tags 
  36.  
  37.   $sc = array('br','input','img','hr','meta','link'); 
  38.  
  39.   // ,'frame','iframe','param','area','base','basefont','col' 
  40.  
  41.   // should not skip tags that can have content inside! 
  42.  
  43.   for ($i=0; $i < $len_opened; $i++) 
  44.  
  45.   { 
  46.  
  47.    $ot = strtolower($opentags[$i]); 
  48.  
  49.    if (!in_array($opentags[$i], $closetags) && !in_array($ot,$sc)) 
  50.  
  51.    { 
  52.  
  53.     $html .= '<!--'.$opentags[$i].'-->'; 
  54.  
  55.    } 
  56.  
  57.    else 
  58. //Vevb.com 
  59.    { 
  60.  
  61.     unset($closetags[array_search($opentags[$i], $closetags)]); 
  62.  
  63.    } 
  64.  
  65.   } 
  66.  
  67.   return $html; 
  68.  
  69. } 

测试使用的结果:

  1. <?php 
  2.  
  3. $content = '<div><p><span>越发忙碌的你,是否想给自己放个假?专注工作的你,是否还记得上一次锻炼是什么时候?优伴户外旅行,给你不一样的旅行体验:给心自由,便处处都是风景!'; 
  4.  
  5. echo CloseTags($content); 
  6.  
  7. /* 
  8.  
  9. 返回的结果是: 
  10.  
  11. </span></p><div><p><span> 
  12.  
  13. 越发忙碌的你,是否想给自己放个假?专注工作的你,是否还记得上一次锻炼是什么时候?优伴户外旅行,给你不一样的旅行体验:给心自由,便处处都是风景!</span></p></div> 
  14.  
  15. */ 
  16.  
  17. ?> 
  18.  
  19. </div> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表