PHP: Count specific Character in String
Tip by Axuter | Last update on 2024-01-16 | 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
The author has not added a profile short description yet.
Show Profile
Related Topics
Mouseover buttons using CSS without reloading
Tutorial | 0 Comments
MySQL: Line Breaks in MySQL
Tip | 0 Comments
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
jQuery: Count characters from multiple input fields
Tip | 0 Comments
PHP: Remove all empty elements from string array
Tip | 0 Comments
Delphi/Lazarus: Display Text of long ListBox Items as Hint
Tutorial | 0 Comments
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 article on askingbox.com. That’s how it’s done.