Example of the string functions substr, iconv_substr, and mb_substr intercepted by php and their advantages and disadvantages

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.