When using php to intercept Chinese strings, two functions, iconv_substr and mb_substr, are frequently used. how should I select these two functions? Refer to the example described in this article to understand. Sample code. the substr and iconv_substr, mb_substr functions are used.
The code is as follows:
Intercept Chinese string _ www.bitsCN.com
$ Str = 'Welcome to 123456 ';
Echo substr ($ str, 0, 4 );
Echo'
';
Echo iconv_substr ($ str, 0,4, 'utf-8 ');
Echo'
';
Echo mb_substr ($ str, 0,4, 'utf-8 ');
?>
Note:
The above code uses two functions, iconv_substr and mb_substr, to intercept strings under the current character, so that Chinese characters can be captured without garbled characters.
How should we choose?
1. The iconv library may run incorrectly on some operating systems. you need to install the GNU extension library to ensure its normal operation. Mb_substr functions have better compatibility.
2. the iconv function converts the current string to the corresponding encoding before intercepting it. the mb function directly intercepts the string based on the specified encoding (secure multi-byte truncation is provided ), therefore, the interception efficiency of the mb function is higher.
Therefore, the mb_substr function is the most suitable choice for intercepting Chinese strings.