php截取html字符串自动补全html标签

文章来总结一下关于利用php截取html字符串自动补全html标签,实际开发中会经常碰到,很多人直接先strip_tags过滤掉html标签,但是就只剩下纯文本了,可读性非常差,下面是一个函数,代码如下:

  1. /**
  2. * 截取HTML,并自动补全闭合
  3. * @param $html
  4. * @param $length
  5. * @param $end
  6. */
  7. function subHtml($html,$length) {
  8. $result = '';
  9. $tagStack = array();
  10. $len = 0;
  11. $contents = preg_split("~(<[^>]+?>)~si",$html, -1,PREG_SPLIT_NO_EMPTY| PREG_SPLIT_DELIM_CAPTURE);
  12. foreach($contents as $tag)
  13. {
  14. if (trim($tag)=="")&nbsp; continue;
  15. if(preg_match("~<([a-z0-9]+)[^/>]*?/>~si",$tag)){
  16. $result .= $tag;
  17. }else if(preg_match("~</([a-z0-9]+)[^/>]*?>~si",$tag,$match)){
  18. if($tagStack[count($tagStack)-1] == $match[1]){
  19. array_pop($tagStack);
  20. $result .= $tag;
  21. }
  22. }else if(preg_match("~<([a-z0-9]+)[^/>]*?>~si",$tag,$match)){
  23. array_push($tagStack,$match[1]);
  24. $result .= $tag;
  25. }else if(preg_match("~<!--.*?-->~si",$tag)){
  26. $result .= $tag;
  27. }else{
  28. if($len + mstrlen($tag) < $length){
  29. $result .= $tag;
  30. $len += mstrlen($tag);
  31. }else {
  32. $str = msubstr($tag,0,$length-$len+1);
  33. $result .= $str;
  34. break;
  35. }
  36. }
  37. }
  38. while(!emptyempty($tagStack)){
  39. $result .= '</'.array_pop($tagStack).'>';
  40. }
  41. return&nbsp; $result;
  42. }
  43. /**
  44. * 截取中文字符串
  45. * @param $string 字符串
  46. * @param $start 起始位
  47. * @param $length 长度
  48. * @param $charset&nbsp; 编码
  49. * @param $dot 附加字串
  50. */
  51. function msubstr($string, $start, $length,$dot='',$charset = 'UTF-8') {
  52. $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;','&nbsp;'), array('&', '"', '<', '>',' '), $string);
  53. if(strlen($string) <= $length) {
  54. return $string;
  55. }
  56. if(strtolower($charset) == 'utf-8') {
  57. $n = $tn = $noc = 0;
  58. while($n < strlen($string)) {
  59. $t = ord($string[$n]);
  60. if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
  61. $tn = 1; $n++;
  62. } elseif(194 <= $t && $t <= 223) {
  63. $tn = 2; $n += 2;
  64. } elseif(224 <= $t && $t <= 239) {
  65. $tn = 3; $n += 3;
  66. } elseif(240 <= $t && $t <= 247) {
  67. $tn = 4; $n += 4;
  68. } elseif(248 <= $t && $t <= 251) {
  69. $tn = 5; $n += 5;
  70. } elseif($t == 252 || $t == 253) {
  71. $tn = 6; $n += 6;
  72. } else {
  73. $n++;
  74. }
  75. $noc++;
  76. if($noc >= $length) {
  77. break;
  78. }
  79. }
  80. if($noc > $length) {
  81. $n -= $tn;
  82. }
  83. $strcut = substr($string, 0, $n);
  84. } else {
  85. for($i = 0; $i < $length; $i++) {
  86. $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
  87. }
  88. }
  89. return $strcut.$dot;
  90. }
  91. /**
  92. * 取得字符串的长度,包括中英文。
  93. */
  94. function mstrlen($str,$charset = 'UTF-8'){
  95. if (function_exists('mb_substr')) {
  96. $length=mb_strlen($str,$charset);
  97. } elseif (function_exists('iconv_substr')) {
  98. $length=iconv_strlen($str,$charset);
  99. } else {//开源代码phpfensi.com
  100. preg_match_all("/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/", $text, $ar);&nbsp;
  101. $length=count($ar[0]);
  102. }
  103. return $length;
  104. }

实例,代码如下:

  1. * @param 要截取的HTML $str
  2. * @param 截取的数量 $num
  3. * @param 是否需要加上更多 $more
  4. * @return 截取串
  5. */
  6. function phpos_chsubstr_ahtml($str,$num,$more=false)
  7. {
  8. $leng=strlen($str);
  9. if($num>=$leng) return $str;
  10. $word=0;
  11. $i=0; /** 字符串指针 **/
  12. $stag=array(array()); /** 存放开始HTML的标志 **/
  13. $etag=array(array()); /** 存放结束HTML的标志 **/
  14. $sp = 0;
  15. $ep = 0;
  16. while($word!=$num)
  17. {
  18. if(ord($str[$i])>128)
  19. {
  20. //$re.=substr($str,$i,3);
  21. $i+=3;
  22. $word++;
  23. }
  24. else if ($str[$i]=='<')
  25. {
  26. if ($str[$i+1] == '!')
  27. {
  28. $i++;
  29. continue;
  30. }
  31. if ($str[$i+1]=='/')
  32. {
  33. $ptag=&$etag ;
  34. $k=&$ep;
  35. $i+=2;
  36. }
  37. else
  38. {
  39. $ptag=&$stag;
  40. $i+=1;
  41. $k=&$sp;
  42. }
  43. for(;$i<$leng;$i++)
  44. {
  45. if ($str[$i] == ' ')
  46. {
  47. $ptag[$k] = implode('',$ptag[$k]);
  48. $k++;
  49. break;
  50. }
  51. if ($str[$i] != '>')
  52. {
  53. $ptag[$k][]=$str[$i];
  54. continue;
  55. }
  56. else
  57. {
  58. $ptag[$k] = implode('',$ptag[$k]);
  59. $k++;
  60. break;
  61. }
  62. }
  63. $i++;
  64. continue;
  65. }
  66. else
  67. {
  68. //$re.=substr($str,$i,1);
  69. $word++;
  70. $i++;
  71. }
  72. }
  73. foreach ($etag as $val)
  74. {
  75. $key1=array_search($val,$stag);
  76. if ($key1 !== false) unset($stag[$key]);
  77. }
  78. foreach ($stag as $key => $val)
  79. {
  80. if (in_array($val,array('br','img'))) unset($stag[$key1]);
  81. }
  82. array_reverse($stag);
  83. $ends = '</'.implode('></',$stag).'>';
  84. $re = substr($str,0,$i).$ends;
  85. if($more) $re.='...';
  86. return $re;
  87. }

PHP截取字符串,生成文章摘要,我们在写BLOG时经常需要显示文章前一部分,但是又怕不恰当截断破坏封闭标签以造成整个文档结构破坏,代码如下:

  1. function text_zhaiyao($text,$length){ //文章摘要生成函数 $test:内容 $length:摘要长度
  2. global $Briefing_Length;
  3. mb_regex_encoding("UTF-8");
  4. if(mb_strlen($text) <= $length ) return $text;
  5. $Foremost = mb_substr($text, 0, $length);
  6. $re = "<(/?)
  7. (P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|TABLE|TR|TD|TH|INPUT|SELECT|TEXTAREA|OBJECT|A|UL|OL|LI|
  8. BASE|META|LINK|HR|BR|PARAM|IMG|AREA|INPUT|SPAN)[^>]*(>?)";
  9. $Single = "/BASE|META|LINK|HR|BR|PARAM|IMG|AREA|INPUT|BR/i";
  10. $Stack = array(); $posStack = array();
  11. mb_ereg_search_init($Foremost, $re, 'i');
  12. while($pos = mb_ereg_search_pos()){
  13. $match = mb_ereg_search_getregs();
  14. /* [Child-matching Formulation]:
  15. $matche[1] : A "/" charactor indicating whether current "<...>" Friction is
  16. Closing Part
  17. $matche[2] : Element Name.
  18. $matche[3] : Right > of a "<...>" Friction
  19. */
  20. if($match[1]==""){
  21. $Elem = $match[2];
  22. if(mb_eregi($Single, $Elem) && $match[3] !=""){
  23. continue;
  24. }