php method to determine the number of characters in a string: 1. Use the strlen() function to get the number of characters in the English string, the syntax is "strlen($str)"; 2. Use the mb_strlen() function , syntax "mb_strlen($str,$encoding)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
How to determine characters in php How many digits does a string have?
Determine how many digits a string has, that is, determine how many characters a string has, that is, get the length of the string.
php provides two built-in functions to get the string length.
strlen(): Get the length of the English string
In the strlen() function, numbers, English, decimal point, underline and space occupy one character length; and one A GB2312 encoded Chinese character occupies two characters in length, and a UTF-8 encoded Chinese character occupies three characters in length.
mb_strlen(): Get the length of Chinese or English string
In the mb_strlen() function, whether it is Chinese characters, English, numbers, decimal points, Underscores and spaces are only one character in length.
1. Use strlen() function
<?php header("Content-type:text/html;charset=utf-8"); $str = "hello world!"; echo '字符串 “'.$str.'” 是:'.strlen($str).' 位的<br>'; $str = "12365"; echo '字符串 “'.$str.'” 是:'.strlen($str).' 位的<br>'; ?>
2. Use The mb_strlen() function
mb_strlen($str,$encoding)
can return the corresponding number of characters by setting the character encoding, which solves the problem of the length of Chinese strings well. . The return value of the
mb_strlen() function is the number of characters contained in the string $str
with $encoding
encoding, if $encoding
If invalid, return false.
<?php header("Content-type:text/html;charset=utf-8"); $str = "hello world!,#%&*@"; echo '字符串 “'.$str.'” 是:'.mb_strlen($str).' 位的<br>'; $str = "欢迎来到PHP中文网"; echo '字符串 “'.$str.'” 是:'.mb_strlen($str,"utf-8").' 位的<br>'; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to determine the number of characters in a string in php. For more information, please follow other related articles on the PHP Chinese website!