22 Votes

PHP: Count specific character in string

Tip by Axuter | Last update on 2020-09-05 | Created on 2013-03-09

In this tip, I would like to show how to count a particular character in a string. 

In the example, we want to determine the number of incidents of the character "|" in a given string.

// our string
$s = '1|2|3|4';

// count characters
$c = substr_count($s, '|');

// output result (3)
echo $c; 

We make use of the function substr_count. This function expects the string as a first parameter and the character to be counted as a second parameter.

Additionally, it is also possible to pass a string consisting of multiple characters as a second parameter to be able to count how often this string is present. Further on, you can also pass an optional third and fourth parameter. The third parameter sets the position from which should be counted and the fourth parameter the length in characters that should be counted at a maximum.


About the Author

AvatarThe author has not added a profile short description yet.
Show Profile


Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.