Mb_strlen and strlen compute string length differences

Source: Internet
Author: User
Keywords Web Programming PHP Tutorials
Tags differences echo http php programming string web

Mb_strlen and strlen compute string length differences

Strlen
int strlen (String $string)

$str = ' 123456 ';
echo strlen ($STR); 6

$STR = ' AB CD http://www.jzread.com '/;
echo strlen ($STR); 20

$ch = ' China ';

echo strlen ($ch);//4

echo Utf8_strlen ($STR); 20
//

function Utf8_strlen ($STR)
{
$count = 0;

    for ($i = 0; $i < strlen ($STR); $i + +)
        {
        $value = Ord ($str [$i]);
        if ($value > 127)
             {
            if $value >= && $value <= 223)
                 $i + +;
            ElseIf ($value >= 224 && $value <= 239)
                $i = $i + 2 ;
            elseif ($value >= && $value <= 247)
                $i = $i + 3;
            Else
                 die (' Not a UTF-8 compatible string ');
           }
      
        $count + +;
        }
  
    return $count
}

Here's a look at the Mb_strlen example
echo ' <br/> ';
$STR = ' China ';
Echo Mb_strlen ($str, ' GBK '); 2 Length of 2, and just when we use strlen when the output of 4, from here can be seen Mb_strlen set his code for GBK when the Chinese processing.
Echo Mb_strlen ($str, ' utf8 ');//3

When we set the Mb_strlen parameter to be UFT8 encoded, his length was 3.

Take a look at the calculation of Chinese and English mixed-row string length instance

$STR = ' Construction Station teaching net http://www.jzread.com/original article ';
Calculated as follows
Echo (strlen ($STR) + Mb_strlen ($str, ' UTF8 '))/2;
Echo
Output results
10
/*
Strlen//Calculate string length, one Chinese when 2 characters
Mb_strlen//According to its character encoding mode, statistic character quot;
In the use of mb_strlen you must put the PHP tutorial. INI php_mbstring.dll front of the ";" Yes, but the general package is gone by default.
Original site article, reprinted annotated Source http://www.jzread.com/

Related Article

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.