主页 > 网站建设 > 建站知识 > dedecms重新定义cn_substr函数截取字数更精准

dedecms重新定义cn_substr函数截取字数更精准

POST TIME:2019-03-20 14:28

,dedecms的cn_substr()和cn_substr_utf8()截取的字符串ms不准,平时也用习惯cn_substr(),也不愿用什么cn_substr_utf8()今天弄了下,现在还是比较准了。按照一个汉字2个字节调用就行了!

方法说明:
一、找到includehelpersstring.helper.php把原来约33到102行(也就是定义cn_substr()函数的那段代码)替换掉,你要是怕不行,可以先把这个文件备份下,亲;

  1. /**
  2. *中英文截取字符串,汉字安2个字节
  3. *
  4. * @accesspublic
  5. * @param string$str 需要截取的字符串
  6. * @param int$cutLen 截取的长度
  7. * @param bool $cutSlashes 是否去掉
  8. * @param bool $addSlashes 是加
  9. * @param string $oDot 截取后加的字符串,如经常用的三个点
  10. * @param bool $hasHtml 是否有html
  11. * @returnstring
  12. */
  13. if ( ! function_exists(‘cn_substr’)){
  14. function cn_substr($str, $cutLen, $oDot = null, $hasHtml = false, $cutSlashes = false, $addSlashes = false) {
  15. global $cfg_soft_lang;
  16. $str = trim ( $str );
  17. if ($cutSlashes) $str = stripslashes ( $str );
  18. if($hasHtml){
  19. $str = preg_replace ( “/(&;[^&;]*&;| | |s|[.+?])/is”, ‘ ‘, $str );
  20. $str = htmlspecialchars ( $str );
  21. }else{
  22. $str = htmlspecialchars ( $str );
  23. }
  24. if ($cutLen && strlen ( $str ) > $cutLen) {
  25. $nStr = ”;
  26. if ($cfg_soft_lang == ‘utf-8′) {
  27. $n = 0;
  28. $tn = 0;
  29. $noc = 0;
  30. while ( $n < strlen ( $str ) ) {
  31. $t = ord ( $str [$n] );
  32. if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
  33. $tn = 1;
  34. $n ++;
  35. $noc ++;
  36. } elseif (194 <= $t && $t <= 223) {
  37. $tn = 2;
  38. $n += 2;
  39. $noc += 2;
  40. } elseif (224 <= $t && $t < 239) {
  41. $tn = 3;
  42. $n += 3;
  43. $noc += 2;
  44. } elseif (240 <= $t && $t <= 247) {
  45. $tn = 4;
  46. $n += 4;
  47. $noc += 2;
  48. } elseif (248 <= $t && $t <= 251) {
  49. $tn = 5;
  50. $n += 5;
  51. $noc += 2;
  52. } elseif ($t == 252 || $t == 253) {
  53. $tn = 6;
  54. $n += 6;
  55. $noc += 2;
  56. } else {
  57. $n ++;
  58. }
  59. if ($noc >= $cutLen)break;
  60. }
  61. if ($noc > $cutLen) $n -= $tn;
  62. $nStr = substr ( $str, 0, $n );
  63. } else {
  64. for($i = 0; $i < $cutLen – 1; $i ++) {
  65. if (ord ( $str [$i] ) > 127) {
  66. $nStr .= $str [$i] . $str [$i + 1];
  67. $i ++;
  68. } else {
  69. $nStr .= $str [$i];
  70. }
  71. }
  72. }
  73. $str = $nStr . $oDot;
  74. }
  75. if ($addSlashes) $str = addslashes ( $str );
  76. $str = htmlspecialchars_decode ( $str );
  77. return trim ( $str );
  78. }
  79. }

二、全站都使用cn_substr()函数,不管你程序是gbk还是utf8;
比如你要调用10个字(拼音汉字混杂):[field:title function='cn_substr(@me,20)']即可



收缩
  • 微信客服
  • 微信二维码
  • 电话咨询

  • 400-1100-266