php字符串截取函数

在php中有一款字符串截取函数substr但这款函数,只能截取英文不支持中文与其它的混体,下面我们提供了三款函数,它们可以支持中英文混合体,实例代码如下:

  1. function syssubstr($string,$length,$append = false)
  2. {
  3. if (strlen($string) < = $length )
  4. {
  5. return $string;
  6. }
  7. else
  8. {
  9. $i = 0;
  10. while ($i < $length)
  11. {
  12. $stringtmp = substr($string,$i,1);
  13. if ( ord($stringtmp) >=224 )
  14. {
  15. $stringtmp = substr($string,$i,3);
  16. $i = $i + 3;
  17. }
  18. elseif( ord($stringtmp) >=192 )
  19. {
  20. $stringtmp = substr($string,$i,2);
  21. $i = $i + 2;
  22. }
  23. else
  24. {
  25. $i = $i + 1;
  26. }
  27. $stringlast[] = $stringtmp;
  28. }
  29. $stringlast = implode("",$stringlast);
  30. if($append)
  31. {
  32. $stringlast .= "...";
  33. }
  34. return $stringlast;
  35. }
  36. }
  37. $string = "";
  38. $length = "18";
  39. $append = false;
  40. echo syssubstr($string,$length,$append);

字符串截取函数二,实例代码如下:

  1. function cut_str($string,$sublen,$start=0,$code='utf-8')
  2. {
  3. if($code=='utf-8')
  4. {
  5. $pa="/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef]
  6. [x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf]
  7. [x80-xbf][x80-xbf]/";
  8. preg_match_all($pa,$string,$t_string);
  9. if(count($t_string[0])-$start>$sublen) return join('',array_slice
  10. ($t_string[0],$start,$sublen))."...";
  11. return join('',array_slice($t_string[0],$start,$sublen));
  12. }
  13. else
  14. {
  15. $start=$start*2;
  16. $sublen=$sublen*2;
  17. $strlen=strlen($string);
  18. $tmpstr='';
  19. for($i=0;$i<$strlen;$i++)
  20. {
  21. if($i>=$start&&$i<($start+$sublen))
  22. {
  23. if(ord(substr($string,$i,1))>129)
  24. {
  25. $tmpstr.=substr($string,$i,2);
  26. }
  27. else
  28. {
  29. $tmpstr.=substr($string,$i,1);
  30. }
  31. }
  32. if(ord(substr($string,$i,1))>129) $i++;
  33. }
  34. if(strlen($tmpstr)<$strlen ) $tmpstr.="...";
  35. return $tmpstr;
  36. }
  37. }
  38. $str="新程php培训";
  39. echo cut_str($str,8,0,'gb2312');

函数三,实例代码如下:

  1. <?php
  2. //截取utf8字符串
  3. function utf8substr($str, $from, $len)
  4. {
  5. return preg_replace('#^(?:[x00-x7f]|[xc0-xff][x80-xbf]+)
  6. {0,'.$from.'}'.
  7. '((?:[x00-x7f]|[xc0-xff][x80-xbf]+){0,'.$len.'}).*#s',
  8. '$1',$str); //开源软件:phpfensi.com
  9. }
  10. ?>

上面三款函数都很好对中文字符等进行截取了,好了不说多了这些都是来自于网络.