2 2 Votes

PHP: Count specific character in string

Tip by Axuter | 09/03/2013 at 19:58

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.

ReplyPositiveNegative

About the Author

Avatar AuthorThe author has not added a short description to his profile yet.
Show Profile | Message

 

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.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.