smarty 的 modifier插件
1、截取gb2312字符串:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 function smarty_modifier_truncate_cn_gb2312($string, $length, $etc = '...')
2 {
3 $result = '';
4 $string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, 'GB2312');
5 $strlen = strlen($string);
6
7 for ($i = 0; (($i < $strlen) && ($length > 0)); $i++)
8 {
9 if (ord(substr($string, $i, 1)) > 128)
10 {
11 if ($length < 1.0)
12 {
13 break;
14 }
15 $result .= substr($string, $i, 2);
16 $length -= 1.0;
17 $i++;
18 }
19 else
20 {
21 $result .= substr($string, $i, 1);
22 $length -= 0.5;
23 }
24 }
25
26 $result = htmlspecialchars($result, ENT_QUOTES, 'GB2312');
27
28 if ($i < $strlen)
29 {
30 $result .= $etc;
31 }
32
33 return $result;
34 }
2、截取UTF-8字符串:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 function smarty_modifier_truncate_cn_utf8($string, $length, $etc = '...')
2 {
3 $result = '';
4 $string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, 'UTF-8');
5 $strlen = strlen($string);
6
7 for ($i = 0; (($i < $strlen) && ($length > 0)); $i++)
8 {
9 if ($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, '0', STR_PAD_LEFT), '0'))
10 {
11 if ($length < 1.0)
12 {
13 break;
14 }
15
16 $result .= substr($string, $i, $number);
17 $length -= 1.0;
18 $i += $number - 1;
19 }
20 else
21 {
22 $result .= substr($string, $i, 1);
23 $length -= 0.5;
24 }
25 }
26
27 $result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
28
29 if ($i < $strlen)
30 {
31 $result .= $etc;
32 }
33
34 return $result;
35 }