Example explanation of the commonly used string length functions strlen() and mb_strlen() in php

int strlen ( string $string ) 

int strlen ( string $string ) Get the length in [bytes] of the given string. Returns the length of string $string on success, or 0 if $string is empty.

<?php
	$str1 = "abcdef"; //output 6
	$str2 = " ab cd "; //output 7, pay attention to the spaces at the beginning, end, and middle
	$str3 = "Hello China"; //Output 12, but it will change, which is related to the character encoding method used by the system
	$str4 = "Hello, China"; //Output 15, but it will change, which is related to the character encoding method used by the system
	echo 'The byte length of $str1 is: '.strlen($str1).' The byte length of $str2 is: '.strlen($str2).'';
	echo 'The byte length of $str3 is: '.strlen($str3).' The byte length of $str4 is: '.strlen($str4).'';
?>

 mb_strlen() — get the length of a string

mixed mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] )
$str String
$encoding to check the length, you can specify the character encoding, if omitted, use the internal character encoding
Return value: return a string with encoding encoding [number of characters] contained in str , multibyte characters are counted as 1

<?php
	$str1 = "abcdef"; //output 6
	$str2 = "ab cd "; //Output 7 Note, spaces at the beginning, end, and middle
	$str3 = "Hello China"; //output 4
	$str4 = "Hello China"; //output 5
	echo 'The character length of $str1 is: '.mb_strlen($str1,"utf-8").'The character length of $str2 is: '.mb_strlen($str2,"utf-8").'';
	echo 'The character length of $str3 is: '.mb_strlen($str3,"utf-8").'The character length of $str4 is: '.mb_strlen($str4,"utf-8").'';
?>

 

 Example explanation of the commonly used string length functions strlen() and mb_strlen() in php

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326760004&siteId=291194637