/**
- @ Truncate a Chinese string for GB2312 encoding
- @ Http://bbs.it-home.org
- */
- Function FSubstr ($ title, $ start, $ len = "", $ magic = true)
- {
- $ Length = 0;
- If ($ len = "") $ len = strlen ($ title );
// Judge the starting position as incorrect
- 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 {
- $ Ctype = 0;
- $ Cstep = 0;
- $ Cur = substr ($ title, $ I, 1 );
- If ($ cur = "&")
- {
- If (substr ($ title, $ I, 4) = "<")
- {
- $ Cstep = 4;
- $ Length + = 4;
- $ I + = 3;
- $ Realnum ++;
- If ($ magic)
- {
- $ Alen ++;
- }
- }
- Else if (substr ($ title, $ I, 4) = "> ")
- {
- $ Cstep = 4;
- $ Length + = 4;
- $ I + = 3;
- $ Realnum ++;
- If ($ magic)
- {
- $ Alen ++;
- }
- }
- Else if (substr ($ title, $ I, 5) = "&")
- {
- $ Cstep = 5;
- $ Length + = 5;
- $ I + = 4;
- $ Realnum ++;
- If ($ magic)
- {
- $ Alen ++;
- }
- }
- Else if (substr ($ title, $ I, 6) = """)
- {
- $ Cstep = 6;
- $ Length + = 6;
- $ I + = 5;
- $ Realnum ++;
- If ($ magic)
- {
- $ Alen ++;
- }
- }
- Else if (substr ($ title, $ I, 6) = "'")
- {
- $ Cstep = 6;
- $ Length + = 6;
- $ I + = 5;
- $ Realnum ++;
- If ($ magic)
- {
- $ Alen ++;
- }
- }
- Else if (preg_match ("/& # (\ d +);/I", substr ($ title, $ I, 8), $ match ))
- {
- $ Cstep = strlen ($ match [0]);
- $ Length + = strlen ($ match [0]);
- $ I + = strlen ($ match [0])-1;
- $ Realnum ++;
- If ($ magic)
- {
- $ Blen ++;
- $ Ctype = 1;
- }
- }
- } Else {
- If (ord ($ cur) >=128)
- {
- $ Cstep = 2;
- $ Length + = 2;
- $ I + = 1;
- $ Realnum ++;
- If ($ magic)
- {
- $ Blen ++;
- $ Ctype = 1;
- }
- } Else {
- $ Cstep = 1;
- $ Length + = 1;
- $ Realnum ++;
- If ($ magic)
- {
- $ Alen ++;
- }
- }
- }
If ($ magic)
- {
- If ($ blen * 2 + $ alen) = ($ len * 2) break;
- If ($ blen * 2 + $ alen) = ($ len * 2 + 1 ))
- {
- If ($ ctype = 1)
- {
- $ Length-= $ cstep;
- Break;
- } Else {
- Break;
- }
- }
- } Else {
- If ($ realnum = $ len) break;
- }
- }
Unset ($ cur );
- Unset ($ alen );
- Unset ($ blen );
- Unset ($ realnum );
- Unset ($ ctype );
- Unset ($ cstep );
Return substr ($ title, $ start, $ length );
- }
- ?>
Copy the above code and test it on your php platform. if you have more hands-on operations, the horizontal improvement will be faster. Programmer's house, a good friend on your way to learning. |