CodeIs to look at the specifications, copy and modify, hope it is perfect...
/* **************************************** * ***************************** Func Name: substrex ** Description: * truncated string by length *** parameters: * $ sstring [String]: string * $ nlength [int]: length * $ sdot [String = "... "]: truncation character * $ scharset [String =" UTF-8 "]: encoding ** returns: [bool] Save the result *********************************** ********************************** */ Function Substrex ( $ Sstring , $ Nlength , $ Sdot = "...",$ Scharset = "UTF-8" ){ If ( Strlen ( $ Sstring ) <= $ Nlength ){ Return $ Sstring ;} $ Sstring = Str_replace ( Array ("&", "\" "," <","> "), Array ("&", "\" "," <","> "), $ Sstring ); $ Sstrcut = "" ; If ( Strtoupper ( $ Scharset ) = "UTF-8" ){ $ NPOs = 0 ; $ Nwordlen = 0 ; $ NOC = 0; // Single-byte characters + 1, multi-byte + 2 (the length of non-single-byte characters is regarded as 2 [should be visual]) While ( $ NPOs < Strlen ( $ Sstring )){ $ T = ORD ( $ Sstring [ $ NPOs ]); If ( $ T = 9 | $ T = 10 | (32 <= $ T && $ T <= 126 )){ $ Nwordlen = 1 ; $ NOC ++ ;} Elseif (194 <= $ T && $ T <= 223 ){ $ Nwordlen = 2; $ NOC + = 2 ;} Elseif (224 <= $ T && $ T <= 239 ){ $ Nwordlen = 3 ; $ NOC + = 2 ;} Elseif (240 <= $ T &&$ T <= 247 ){ $ Nwordlen = 4 ; $ NOC + = 2 ;} Elseif (248 <= $ T && $ T <= 251 ){ $ Nwordlen = 5 ; $ NOC + = 2;} Elseif ( $ T = 252 | $ T = 253 ){ $ Nwordlen = 6 ; $ NOC + = 2 ;} Else { $ Nwordlen = 0 ;} $ NPOs + = ( $ Nwordlen > 0 )? $ Nwordlen : 1 ; If ( $ NOC > = $ Nlength ){ Break ;}} If ( $ NOC > $ Nlength ){ $ NPOs -= $ Nwordlen ;} $ Sstrcut = Substr ( $ Sstring , 0, $ NPOs );} Else { For ( $ I = 0; $ I < $ Nlength ; $ I ++){ $ Sstrcut . = ORD ( $ Sstring [ $ I ])> 127? $ Sstring [ $ I ]. $ Sstring [++ $ I ]: $ Sstring [ $ I ] ;}} $ Sstrcut =Str_replace ( Array ("&", "\" "," <","> "), Array ("&", "\" "," <","> "), $ Sstrcut ); Return $ Sstrcut . $ Sdot ;}