首页 > CMS教程 > DEDECMS > 正文

dedecms怎么重新定义cn_substr函数截取字数更准确

藏色散人
发布: 2019-12-25 09:54:30
原创
1989人浏览过

dedecms怎么重新定义cn_substr函数截取字数更准确

dedecms怎么重新定义cn_substr函数截取字数更准确?

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

推荐学习:织梦cms

  

方法说明:

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

阿里云-虚拟数字人
阿里云-虚拟数字人

阿里云-虚拟数字人是什么? ...

阿里云-虚拟数字人 2
查看详情 阿里云-虚拟数字人

代码如下:

/** 
* 中英文截取字符串,汉字安2个字节 
* 
* @access public 
* @param string $str 需要截取的字符串 
* @param int $cutLen 截取的长度 
* @param bool $cutSlashes 是否去掉\ 
* @param bool $addSlashes 是加\ 
* @param string $oDot 截取后加的字符串,如经常用的三个点 
* @param bool $hasHtml 是否有html 
* @return string 
*/ 
if ( ! function_exists(‘cn_substr’)){ 
function cn_substr($str, $cutLen, $oDot = null, $hasHtml = false, $cutSlashes = false, $addSlashes = false) { 
global $cfg_soft_lang; 
$str = trim ( $str ); 
if ($cutSlashes) $str = stripslashes ( $str ); 
if($hasHtml){ 
$str = preg_replace ( “/(\<[^\<]*\>|\r|\n|\s|\[.+?\])/is”, ‘ ‘, $str ); 
$str = htmlspecialchars ( $str ); 
}else{ 
$str = htmlspecialchars ( $str ); 
} 
if ($cutLen && strlen ( $str ) > $cutLen) { 
$nStr = ”; 
if ($cfg_soft_lang == ‘utf-8′) { 
$n = 0; 
$tn = 0; 
$noc = 0; 
while ( $n < strlen ( $str ) ) { 
$t = ord ( $str [$n] ); 
if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) { 
$tn = 1; 
$n ++; 
$noc ++; 
} elseif (194 <= $t && $t <= 223) { 
$tn = 2; 
$n += 2; 
$noc += 2; 
} elseif (224 <= $t && $t < 239) { 
$tn = 3; 
$n += 3; 
$noc += 2; 
} elseif (240 <= $t && $t <= 247) { 
$tn = 4; 
$n += 4; 
$noc += 2; 
} elseif (248 <= $t && $t <= 251) { 
$tn = 5; 
$n += 5; 
$noc += 2; 
} elseif ($t == 252 || $t == 253) { 
$tn = 6; 
$n += 6; 
$noc += 2; 
} else { 
$n ++; 
} 
if ($noc >= $cutLen)break; 
} 
if ($noc > $cutLen) $n -= $tn; 
$nStr = substr ( $str, 0, $n ); 
} else { 
for($i = 0; $i < $cutLen – 1; $i ++) { 
if (ord ( $str [$i] ) > 127) { 
$nStr .= $str [$i] . $str [$i + 1]; 
$i ++; 
} else { 
$nStr .= $str [$i]; 
} 
} 
} 
$str = $nStr . $oDot; 
} 
if ($addSlashes) $str = addslashes ( $str ); 
$str = htmlspecialchars_decode ( $str ); 
return trim ( $str ); 
} 
}
登录后复制

二、全站都使用cn_substr()函数,不管你程序是gbk还是utf8;

比如你要调用10个字(拼音汉字混杂):[field:title function='cn_substr(@me,20)']即可

以上就是dedecms怎么重新定义cn_substr函数截取字数更准确的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号