当前位置:首页 > PHP教程 > php高级应用 > 列表

PHP实现补齐关闭的HTML标签

发布:smiling 来源: PHP粉丝网  添加日期:2021-07-20 22:14:46 浏览: 评论:0 

这篇文章主要介绍了PHP实现补齐关闭的HTML标签的方法,通过自定义函数实现针对HTML标签的闭合补全功能,涉及PHP字符串及正则匹配相关操作技巧,需要的朋友可以参考下。

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

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

  1. function CloseTags($html) 
  2. { 
  3.   // 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!) 
  4.   $html = preg_replace('/<[^>]*$/','',$html); // ending with fraction of open tag 
  5.   // put open tags into an array 
  6.   preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result); 
  7.   $opentags = $result[1]; 
  8.   // put all closed tags into an array 
  9.   preg_match_all('#</([a-z]+)>#iU', $html, $result); 
  10.   $closetags = $result[1]; 
  11.   $len_opened = count($opentags); 
  12.   // if all tags are closed, we can return 
  13.   if (count($closetags) == $len_opened) { 
  14.    return $html; 
  15.   } 
  16.   // close tags in reverse order that they were opened 
  17.   $opentags = array_reverse($opentags); 
  18.   // self closing tags 
  19.   $sc = array('br','input','img','hr','meta','link'); 
  20.   // ,'frame','iframe','param','area','base','basefont','col' 
  21.   // should not skip tags that can have content inside! 
  22.   for ($i=0; $i < $len_opened; $i++) 
  23.   { 
  24.    $ot = strtolower($opentags[$i]); 
  25.    if (!in_array($opentags[$i], $closetags) && !in_array($ot,$sc)) 
  26.    { 
  27.     $html .= '</'.$opentags[$i].'>'; 
  28.    } 
  29.    else 
  30.    { 
  31.     unset($closetags[array_search($opentags[$i], $closetags)]); 
  32.    } 
  33.   } 
  34.   return $html; 
  35. } 

测试使用的结果:

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

Tags: PHP补齐关闭 HTML标签

分享到: