Sample and Analysis of php string functions substr, iconv_substr, and mb_substr

Source: Internet
Author: User

Sample Code. The substr and iconv_substr, mb_substr functions are used.

Copy codeThe Code is as follows:
<Html>
<Head> <meta charset = 'utf-8'>
<Title> intercept a Chinese string _ foothome _ www.jb51.net </title>
</Head>
<Body>
<? Php
$ Str = 'Welcome to home of 123 ';
Echo substr ($ str, 0, 4 );
Echo '<br> ';
Echo iconv_substr ($ str, 0,4, 'utf-8 ');
Echo '<br> ';
Echo mb_substr ($ str, 0,4, 'utf-8 ');
?>
</Body>
</Html>

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.