This article mainly introduces the php Chinese truncation functions mb_strlen and mb_substr, which can be replaced by this function when the server does not have an mbstring library. For more information, see
This article mainly introduces the php Chinese truncation functions mb_strlen and mb_substr, which can be replaced by this function when the server does not have an mbstring library. For more information, see
As we all know, the strlen and substr functions provided by php cannot process Chinese characters, so we will use the mb _ series functions instead. But what if there is no mbstring library? In this case, we need to write one ourselves to replace it. If you don't talk much about it, first go to the Code:
The Code is as follows:
If (! Function_exists ('mb _ strlen ')){
Function mb_strlen ($ text, $ encode ){
If ($ encode = 'utf-8 '){
Return preg_match_all ('% (? :
[\ X09 \ x0A \ x0D \ x20-\ x7E] # ASCII
| [\ XC2-\ xDF] [\ x80-\ xBF] # non-overlong 2-byte
| \ XE0 [\ xA0-\ xBF] [\ x80-\ xBF] # excluding overlongs
| [\ XE1-\ xEC \ xEE \ xEF] [\ x80-\ xBF] {2} # straight 3-byte
| \ XED [\ x80-\ x9F] [\ x80-\ xBF] # excluding surrogates
| \ XF0 [\ x90-\ xBF] [\ x80-\ xBF] {2} # planes 1-3
| [\ XF1-\ xF3] [\ x80-\ xBF] {3} # planes 4-15
| \ XF4 [\ x80-\ x8F] [\ x80-\ xBF] {2} # plane 16
) % Xs ', $ text, $ out );
} Else {
Return strlen ($ text );
}
}
}
/* From Internet, author unknown */
If (! Function_exists ('mb _ substr ')){
Function mb_substr ($ str, $ start, $ len = '', $ encoding =" UTF-8 "){
$ Limit = strlen ($ str );
For ($ s = 0; $ start> 0; -- $ start) {// found the real start
If ($ s >=$ limit)
Break;
If ($ str [$ s] <= "\ x7F ")
++ $ S;
Else {
+ $ S; // skip length
While ($ str [$ s] >=" \ x80 "& $ str [$ s] <=" \ xBF ")
++ $ S;
}
}
If ($ len = '')
Return substr ($ str, $ s );
Else
For ($ e = $ s; $ len> 0; -- $ len) {// found the real end
If ($ e >=$ limit)
Break;
If ($ str [$ e] <= "\ x7F ")
++ $ E;
Else {
++ $ E; // skip length
While ($ str [$ e] >=" \ x80 "& $ str [$ e] <=" \ xBF "& $ e <$ limit)
++ $ E;
}
}
Return substr ($ str, $ s, $ e-$ s );
}
}