欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php中文截取字符串函数(很好用)

程序员文章站 2022-06-10 20:34:21
...
  1. /**

  2. * 中文字符串截取函数
  3. * by bbs.it-home.org
  4. */
  5. function cut_str($string,$sublen,$filter=true,$start=0,$code='UTF-8'){
  6. if($filter) $string=Html2Text($string);
  7. if($code=='UTF-8'){
  8. $pa="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  9. preg_match_all($pa,$string,$t_string);
  10. if(count($t_string[0])-$start>$sublen) return join('',array_slice($t_string[0],$start,$sublen))."...";
  11. return join('',array_slice($t_string[0],$start,$sublen));
  12. }else{
  13. $start=$start*2;
  14. $sublen=$sublen*2;
  15. $strlen=strlen($string);
  16. $tmpstr='';
  17. for($i=0;$i if($i>=$start&&$i if(ord(substr($string,$i,1))>129){
  18. $tmpstr.=substr($string,$i,2);
  19. }else{
  20. $tmpstr.=substr($string,$i,1);
  21. }
  22. }
  23. if(ord(substr($string,$i,1))>129) $i++;
  24. }
  25. if(strlen($tmpstr) return $tmpstr;
  26. }
  27. }
  28. //html转换函数

  29. function Html2Text($str){
  30. $str = preg_replace("/||/isU","",$str);
  31. $alltext = "";
  32. $start = 1;
  33. for($i=0;$i if($start==0 && $str[$i]==">"){
  34. $start = 1;
  35. }else if($start==1){
  36. if($str[$i]==" $start = 0;
  37. $alltext .= " ";
  38. }else if(ord($str[$i])>31){
  39. $alltext .= $str[$i];
  40. }
  41. }
  42. }
  43. $alltext = str_replace(" "," ",$alltext);
  44. $alltext = preg_replace("/&([^;&]*)(;|&)/","",$alltext);
  45. $alltext = preg_replace("/[ ]+/s"," ",$alltext);
  46. return $alltext;
  47. }
复制代码