![]() |
VOOZH | about |
We have given a string and the task is to count number of characters in a string str in PHP. In order to do this task, we have the following methods in PHP:
Table of Content
The strlen() method is used to get the length of a given string str. Length of the string including all the white spaces and special characters in this method.
Syntax:
strlen( $string )Example :
19
The mb_strlen() method is used to return the number of characters in a string having character encoding. A multi-byte character is counted as 1.
Syntax:
mb_strlen($str, $encoding);
Note: Before using this function, install the php7.0-mbstring package using the following command:
sudo apt install php7.0-mbstring
Example :
Output
19
The iconv_strlen() method is used to get the character count of a string, as an integer.
Syntax:
int iconv_strlen( string $str,
string $charset = ini_get("iconv.internal_encoding"))
Example :
19
The grapheme_strlen() method is used to get the string length in grapheme units (not bytes or characters).
Syntax:
int grapheme_strlen(string $input)
Example :
19
You can count the number of characters in a string using preg_match_all() in PHP. By using a regular expression that matches each character individually, you can count the occurrences of all characters in the string.
Example:
12
Using a for loop in PHP, you can count the number of characters in a string by iterating through each character until the end of the string.
Example:
13
In this approach we iterate through each character of the string using a foreach loop and count them.
Example:
Number of characters: 25