Home > Article > CMS Tutorial > How dedecms redefines the cn_substr function to intercept the number of words more accurately
dedecmsHow to redefine the cn_substr function to intercept the number of words more accurately?
dedecms' cn_substr() and cn_substr_utf8() intercept the string ms. I usually use cn_substr(), but I don't want to use cn_substr_utf8(). I tried it today, and it's still better now. Right. Just call it according to 2 bytes of a Chinese character
Recommended learning:梦weavercms
Method description:
一, find \include\helpers\string.helper.php and replace the original lines 33 to 102 (that is, the code that defines the cn_substr() function). If you are afraid, you can back up this file first, dear;
The code is as follows:
/** * 中英文截取字符串,汉字安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 ); } }
2. The entire site uses the cn_substr() function, regardless of whether your program is gbk or utf8;
For example, if you want to call 10 characters (Pinyin Mixed Chinese characters): [field:title function='cn_substr(@me,20)'] can
The above is the detailed content of How dedecms redefines the cn_substr function to intercept the number of words more accurately. For more information, please follow other related articles on the PHP Chinese website!