Analysis of the Usage Examples of php Common String Length Functions strlen of and mb_strlen of

  • 2021-12-12 08:04:11
  • OfStack

This article illustrates the usage of php string length functions strlen () and mb_strlen (). Share it for your reference, as follows:

int strlen ( string $string )

int strlen (string $string) Gets the length of the given string in [bytes]. If successful, it returns the length of the string $string, and if $string is empty, it returns 0.


<?php
  $str1 = "abcdef";    // Output 6
  $str2 = " ab cd ";    // Output 7 , attention , Beginning, ending, middle space 
  $str3 = " Hello, China ";    // Output 12, However, it will change, depending on the character encoding method adopted by the system 
  $str4 = " Hello, China ";  // Output 15, However, it will change, depending on the character encoding method adopted by the system 
  echo '$str1 The byte length of the :'.strlen($str1).'$str2 The byte length of the :'.strlen($str2).'';
  echo "<br/>";
  echo '$str3 The byte length of the :'.strlen($str3).'$str4 The byte length of the :'.strlen($str4).''; 
?>

Run results:

$str1 byte length: 6 $str2 byte length: 7
$str3 byte length: 8 $str4 byte length: 10

mb_strlen ()-Gets the length of the string

mixed mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] )

$str String to check length

$encoding, you can specify character encoding, or use internal character encoding if omitted

Return value: Returns the number of characters contained in the string str with encoding encoding, and multi-byte characters are counted as 1


<?php
  $str1 = "abcdef";    // Output 6
  $str2 = " ab cd ";    // Output 7     Attention , Beginning, ending, middle space 
  $str3 = " Hello, China ";    // Output 4
  $str4 = " Hello, China ";  // Output 5
  echo '$str1 The character length of is :'.mb_strlen($str1,"utf-8").'$str2 The character length of is :'.mb_strlen($str2,"utf-8").'';
  echo "<br/>";
  echo '$str3 The character length of is :'.mb_strlen($str3,"utf-8").'$str4 The character length of is :'.mb_strlen($str4,"utf-8").'';
?>

Run results:

$str1 character length: 6 $str2 character length: 7
$str3 character length: 3 $str4 character length: 5

For more readers interested in PHP related contents, please check the topics of this site: "Summary of Common Functions and Skills of php", "Summary of Usage of php String (string)", "Complete Collection of Operation Skills of PHP Array (Array)", "Introduction to Basic Grammar of PHP", "Introduction to Database Operation of php + mysql" and "Summary of Operation Skills of Common Database of php"

I hope this article is helpful to everyone's PHP programming.


Related articles: