How to find number of characters in a string in PHP ? (original) (raw)
Last Updated : 11 Jul, 2024
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
- Method 1: Using strlen() Method
- Method 2: Using mb_strlen() Method
- Method 3: Using iconv_strlen() Method
- Method 4: Using grapheme_strlen() Method
- Method 5: Using preg_match_all()
- Using for Loop
- Using foreach
**Method 1: Using strlen() Method
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 :
PHP `
len=strlen(len = strlen(len=strlen(str); // Printing the result echo $len; ?>`
**Method 2: Using mb_strlen() Method
The **mb_strlen() methodis 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 :
PHP `
len=mbstrlen(len = mb_strlen(len=mbstrlen(str); // Printing the result echo $len; ?>`
**Output
19
**Method 3: Using iconv_strlen() Method
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 :
PHP `
len=iconvstrlen(len = iconv_strlen(len=iconvstrlen(str); // Printing the result echo $len; ?>`
**Method 4: Using grapheme_strlen() Method
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 :
PHP `
len=graphemestrlen(len = grapheme_strlen(len=graphemestrlen(str); // printing the result echo $len; ?>`
Method 5: Using preg_match_all()
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:
PHP `
string,string, string,matches); numChars=count(numChars = count(numChars=count(matches[0]); echo $numChars; // Output: 12 (including space and punctuation) ?>`
Using for Loop
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:
PHP `
`
Using foreach
In this approach we iterate through each character of the string using a foreach loop and count them.
**Example:
PHP `
`
Output
Number of characters: 25