php源码分析之DZX1.5字符串截断函数cutstr用法

这篇文章主要介绍了php源码分析之DZX1.5字符串截断函数cutstr用法,实例分析了DZX1.5中cutstr函数实现字符串截取的使用技巧,需要的朋友可以参考下。

本文实例讲述了php源码分析之DZX1.5字符串截断函数cutstr用法,分享给大家供大家参考,具体分析如下:

  1. <?php
  2. /**
  3. * 函数来源DZX1.5,文件所在 /source/function/function_core.php
  4. */
  5. define('CHARSET','UTF-8');
  6. function cutstr($string, $length, $dot="...") {
  7. if(strlen($string)<=$length) {
  8. return $string;
  9. }
  10. if(strtolower(CHARSET) == "utf-8") {
  11. $n = $tn = $noc = 0;
  12. while($n < strlen($string)) {
  13. $t = ord($string[$n]);
  14. if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
  15. $tn = 1; $n++; $noc++;
  16. } elseif(194 <= $t && $t <= 223) {
  17. $tn = 2; $n += 2; $noc += 2;
  18. } elseif(224 <= $t && $t <= 239) {
  19. $tn = 3; $n += 3; $noc += 2;
  20. } elseif(240 <= $t && $t <= 247) {
  21. $tn = 4; $n += 4; $noc += 2;
  22. } elseif(248 <= $t && $t <= 251) {
  23. $tn = 5; $n += 5; $noc += 2;
  24. } elseif($t == 252 || $t == 253) {
  25. $tn = 6; $n += 6; $noc += 2;
  26. } else {
  27. $n++;
  28. }
  29. if($noc >= $length) {
  30. break;
  31. }
  32. }
  33. if($noc > $length) {
  34. $n -= $tn;
  35. }
  36. $strcut = substr($string, 0, $n);
  37. } else {
  38. for($i = 0; $i < $length; $i++) {
  39. $strcut .= ord($string[$i])>127 ? $string[$i].$string[++$i] : $string[$i];
  40. }
  41. }
  42. $pos = strrpos($strcut, chr(1));
  43. if($pos !== false) {
  44. $strcut = substr($strcut,0,$pos);
  45. }
  46. return $strcut.$dot;
  47. }
  48. $string = '测试数据库ablci102020@(#)!)!测试劳动力ddk';
  49. echo cutstr($string,15);
  50. /*End of php*/

运行结果如下:

测试数据库ablci1020...