Smarty截取中文擴展,支持UTF-8和GB
1
function smarty_modifier_truncate_cn($string, $length = 80, $code = 'UTF-8', $etc = '
')
2
{
3
if ($length == 0)
4
return '';
5
if($code == 'UTF-8'){
6
$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
7
}
8
else{
9
$pa = "/[\x01-\x7f]|[\xa1-\xff][\xa1-\xff]/";
10
}
11
preg_match_all($pa, $string, $t_string);
12
if(count($t_string[0]) > $length)
13
return join('', array_slice($t_string[0], 0, $length)).$etc;
14
return join('', array_slice($t_string[0], 0, $length));
15
}


2

3

4

5

6

7

8

9

10

11

12

13

14

15

以下代碼保存為ascii格式
1
<html>
2
<head>
3
<title>Truncate 測試</title>
4
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
5
</head>
6
<body>
7
{{$string}}<br>
8
{{$string|truncate_cn:15:"":""}}<br>
9
</body>
10
</html>

2

3

4

5

6

7

8

9

10

以下代碼保存為:UTF-8格式
1
<html>
2
<head>
3
<title>Truncate 測試</title>
4
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
5
</head>
6
<body>
7
{{$string}}<br>
8
{{$string|truncate_cn:15:"UTF-8":"
"}}<br>
9
</body>
10
</html>

2

3

4

5

6

7

8


9

10

posted on 2007-11-20 14:34 編程之道 閱讀(1059) 評論(0) 編輯 收藏 引用 所屬分類: web編程 、開發相關