Phpsubstr truncation of half Chinese characters garbled problem solution
- /**
- * Improved substr
- * Edit bbs.it-home.org
- */
- Function getstr ($ string, $ length, $ encoding = 'utf-8 '){
- $ String = trim ($ string );
- If ($ length & strlen ($ string)> $ length ){
- // Truncation character
- $ Wordscut = '';
- If (strtolower ($ encoding) = 'utf-8 '){
- // Utf8 encoding
- $ N = 0;
- $ Tn = 0;
- $ Noc = 0;
- While ($ n <strlen ($ string )){
- $ T = ord ($ string [$ 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 >=$ length ){
- Break;
- }
- }
- If ($ noc> $ length ){
- $ N-= $ tn;
- }
- $ Wordscut = substr ($ string, 0, $ n );
- } Else {
- For ($ I = 0; $ I <$ length-1; $ I ++ ){
- If (ord ($ string [$ I])> 127 ){
- $ Wordscut. = $ string [$ I]. $ string [$ I + 1];
- $ I ++;
- } Else {
- $ Wordscut. = $ string [$ I];
- }
- }
- }
- $ String = $ wordscut;
- }
- Return trim ($ string );
- }
- ?>
|