Discuz教程网

Discuz 中不使用mb_substr函数切割字符串函数

[复制链接]
authicon dly 发表于 2012-8-3 20:41:29 | 显示全部楼层 |阅读模式
php中要正确切割字符串,使用mb_substr函数是最简单。但是需要编译时使用了  --enable-mbstring安装扩展。在不使用mb_substr怎么能正确切割呢?Discuz的global.func.php中有个解决这个问题的函数。注意: 函数是copy的,使用时请注意版权问题。另外这个函数是按字节切割字符,而不是按字符长度切割字符,就是说一个中文字在gbk的情况下是计算了2。要改为按字符切割做一些小修改就可以了。
  1. function cutstr($string, $length, $dot = ' ...')
  2. {
  3. global $charset;

  4. if(strlen($string) <= $length) return $string;

  5. $string = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string);

  6. $strcut = '';

  7. if(strtolower($charset) == 'utf-8')
  8. {
  9. $n = $tn = $noc = 0;

  10. while($n < strlen($string))
  11. {
  12. $t = ord($string[$n]);

  13. // 特别要注意这部分,utf-8是1--6位不定长表示的,这里就是如何
  14. // 判断utf-8是1位2位还是3位还是4、5、6位,这对其他语言的编程也有用处
  15. // 具体可以查看rfc3629或rfc2279
  16. if($t == 9 || $t == 10 || (32 <= $t && $t <= 126))
  17. {
  18. $tn = 1; $n++; $noc++;
  19. }
  20. elseif(194 <= $t && $t <= 223)
  21. {
  22. $tn = 2; $n += 2; $noc += 2;
  23. }
  24. elseif(224 <= $t && $t < 239)
  25. {
  26. $tn = 3; $n += 3; $noc += 2;
  27. }
  28. elseif(240 <= $t && $t <= 247)
  29. {
  30. $tn = 4; $n += 4; $noc += 2;
  31. }
  32. elseif(248 <= $t && $t <= 251)
  33. {
  34. $tn = 5; $n += 5; $noc += 2;
  35. }
  36. elseif($t == 252 || $t == 253)
  37. {
  38. $tn = 6; $n += 6; $noc += 2;
  39. }
  40. else
  41. {
  42. $n++;
  43. }

  44. if($noc >= $length)
  45. {
  46. break;
  47. }

  48. }

  49. if($noc > $length) $n -= $tn;

  50. $strcut = substr($string, 0, $n);
  51. }
  52. else
  53. {
  54. for($i = 0; $i < $length; $i++)
  55. {
  56. $strcut .= ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];
  57. }
  58. }

  59. $strcut = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $strcut);

  60. return $strcut . $dot;
  61. }
复制代码
使用方法
  1. $testStr = "好好学习!(good good study)天天向上!(day day up)"; // ^_^! V

  2. // 使用utf文档
  3. echo cutstr($testStr, 10);

  4. // 使用dos文档使用以下代码测试utf-8的效果
  5. //$testStr = iconv('GBK', 'UTF-8', $testStr);
  6. //echo iconv('UTF-8', 'GBK', cutstr($testStr, 10));
复制代码



上一篇:discuz论坛深度优化和系统整改
下一篇:SPS Discuz7.2 超强给力修改版 update 2012.02.14
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-2 03:28

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表