当前位置:Gxlcms > PHP教程 > 适用于不同编码的中文字符串截取函数代码实例汇总

适用于不同编码的中文字符串截取函数代码实例汇总

时间:2021-07-01 10:21:17 帮助过:8人阅读

1. 适用于GB2312中文字符串

  1. <?php
  2. //截取中文字符串
  3. function mysubstr($str, $start, $len) {
  4. $tmpstr = "";
  5. $strlen = $start + $len;
  6. for($i = 0; $i < $strlen; $i++) {
  7. if(ord(substr($str, $i, 1)) > 0xa0) {
  8. $tmpstr .= substr($str, $i, 2);
  9. $i++;
  10. } else
  11. $tmpstr .= substr($str, $i, 1);
  12. }
  13. return $tmpstr;
  14. }
  15. ?>

2. 适用于utf8

  1. <?php
  2. //截取utf8字符串
  3. function utf8Substr($str, $from, $len)
  4. {
  5. return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
  6. '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
  7. '$1',$str);
  8. }
  9. ?>

3。全部都适用

  1. function csubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
  2. {
  3. if(function_exists("mb_substr"))
  4. return mb_substr($str, $start, $length, $charset);
  5. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  6. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  7. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  8. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  9. preg_match_all($re[$charset], $str, $match);
  10. $slice = join("",array_slice($match[0], $start, $length));
  11. if($suffix) return $slice."…";
  12. return $slice;
  13. }

4. BugFree 的字符截取函数

  1. <?php
  2. function sysSubStr($String,$Length,$Append = false)
  3. {
  4. if (strlen($String) <= $Length )
  5. {
  6. return $String;
  7. }
  8. else
  9. {
  10. $I = 0;
  11. while ($I < $Length)
  12. {
  13. $StringTMP = substr($String,$I,1);
  14. if ( ord($StringTMP) >=224 )
  15. {
  16. $StringTMP = substr($String,$I,3);
  17. $I = $I + 3;
  18. }
  19. elseif( ord($StringTMP) >=192 )
  20. {
  21. $StringTMP = substr($String,$I,2);
  22. $I = $I + 2;
  23. }
  24. else
  25. {
  26. $I = $I + 1;
  27. }
  28. $StringLast[] = $StringTMP;
  29. }
  30. $StringLast = implode("",$StringLast);
  31. if($Append)
  32. {
  33. $StringLast .= "...";
  34. }
  35. return $StringLast;
  36. }
  37. }$String = "www.at0915.cn";
  38. $Length = "18";
  39. $Append = false;
  40. echo sysSubStr($String,$Length,$Append);
  41. ?>

以上就是适用于不同编码的中文字符串截取函数代码实例汇总的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行