Differentiation of string lengths in different php codes _ PHP Tutorial-php Tutorial

Source: Internet
Author: User
The length of php strings varies according to the encoding. Is the Chinese character string of the UTF-8 three bytes? Php coding UTF-8echostrlen (test text a test text); echo-; echomb_strlen (test text a test text, UTF-8 );? Output: The Chinese string of the 25-9 GB UTF-8 is three bytes

// Coding UTF-8
Echo strlen ('test text a test text ');
Echo '-';
Echo mb_strlen ('test text a test text', 'utf-8 ');
?>
Output: 25-9

The Chinese string of GB2312 is two bytes.

// Code GB2312
Echo strlen ('test text a test text ');
Echo '-';
Echo mb_strlen ('test text a test text', 'gb2312 ');
?>
Output: 17-9

In Mysql databases (versions later than Mysql 5.1), if the field type is varchar (10), you can insert 10 characters (not Bytes );
Therefore, the length of a string must be determined by document encoding.

Character string truncation in a simple UTF-8 (by number of characters)

/*
* UTF-8 string truncation
* $ Str string to be intercepted
* $ Start: the starting position of the truncation.
* $ Length: truncation length
*/
Function cutStr ($ str, $ start, $ length ){
$ Restr = '';
$ J = 0;
$ End = $ length + $ start-1;
$ Plen = strlen ($ str );
For ($ I = 0; $ I <$ plen; $ I ++ ){
$ Restr. = ord ($ str [$ I])> 127? $ Str [$ I]. $ str [++ $ I]. $ str [++ $ I]: $ str [$ I];
$ J ++;
If ($ j <$ start) {$ restr = '';}
If ($ j >=$ end) {break ;}
}
$ Restr. = '';
Return $ restr;
}

$ Str = 'xinnet, September 11, September 24 (G20) leaders will hold the third financial summit in Pittsburgh, USA Today. ';
Echo $ str;
Echo'
';
Echo utf8_substr ($ str, 0, 25 );
Echo'
';
?>

Why? Php // coding UTF-8 echo strlen ('test text a test text'); echo '-'; echo mb_strlen ('test text a test text ', 'utf-8 ');? Output: 25-9 GB...

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.