以下代码试用于GB2312编码,截取中文字符串是PHP中一个头疼的问题,解决方法是根据值是否大于等于128来判断是否是双字节字符,以避免出现乱码的情况。但中英文混合、特殊符号等问题总是存在,现在写一个比较全面的,仅供参考:
程序说明:
1. len 参数以中文字符为标准,1len等于2个英文字符,为了形式上好看些
2. 如果将magic参数设为false,则中文和英文同等看待,取绝对的字符数
3. 特别适用于用htmlspecialchars()进行过编码的字符串
4. 能正确处理GB2312中实体字符模式()
程序代码:
function FSubstr($title,$start,$len="",$magic=true)
{
/**
- powered by Smartpig
- mailto:[email protected]
*/
$length = 0;
if($len == "") $len = strlen($title);
//判断起始为不正确位置
if($start > 0)
{
$cnum = 0;
for($i=0;$i<$start;$i++)
{
if(ord(substr($title,$i,1)) >= 128) $cnum ++;
}
if($cnum%2 != 0) $start--;
unset($cnum);
}
if(strlen($title)<=$len) return substr($title,$start,$len);
$alen = 0;
$blen = 0;
$realnum = 0;
for($i=$start;$i
1<strlen($title);$i++) $alen="" $blen="" $cstep="strlen($match[0]);" $ctype="1;" $cur="substr($title,$i,1);" $i="" $length="" $realnum="" &#(\d+);="" )="" +="strlen($match[0])-1;" ++;="" else="" i",substr($title,$i,8),$match))="" if($cur="&" if($magic)="" if(ord($cur)="" if(preg_match("="" if(substr($title,$i,4)=">" if(substr($title,$i,5)="&" if(substr($title,$i,6)="'" {="" }="" }else{="">=128)
2{
3$cstep = 2;
4$length += 2;
5$i += 1;
6$realnum ++;
7if($magic)
8{
9$blen ++;
10$ctype = 1;
11}
12}else{
13$cstep = 1;
14$length +=1;
15$realnum ++;
16if($magic)
17{
18if(ord($cur) >= 65 && ord($cur) <= 90)
19{
20$blen++;
21}else{
22$alen++;
23}
24}
25}
26}
27
28if($magic)
29{
30if(($blen*2+$alen) == ($len*2)) break;
31if(($blen*2+$alen) == ($len*2+1))
32{
33if($ctype == 1)
34{
35$length -= $cstep;
36break;
37}else{
38break;
39}
40}
41}else{
42if($realnum == $len) break;
43}
44}
45
46unset($cur);
47unset($alen);
48unset($blen);
49unset($realnum);
50unset($ctype);
51unset($cstep);
52
53return substr($title,$start,$length);
54}
55
56呵呵,一会儿把UTF-8编码下的代码也贴出来</strlen($title);$i++)>