Count Specific Characters in a String
The PHP substr_count() function counts how many times specified characters occur in a string.
In other words, it can tell you how many times "stan" occurs in a word or sentence. Or how many times "a" occurs.
As examples, substr_count("substantial","stan") returns the number 1 and substr_count("substantial","a") returns the number 2. There is only one occurrence of "stan" in the string "substantial." And there are two occurrences of "a" in that string.
My use of substr_count() generally is to determine if an amount contains exactly one period, a percentage contains a "%" character, or an email address contains exactly one "@" character. Those types of things. But its use surely is not limited to that.
Here is code to fact-check the above examples.
<?php $string='substantial'; echo '<hr>"stan" occurs '. substr_count($string,"stan") ." time in \"$string.\""; echo '<hr>"a" occurs '. substr_count($string,"a") ." times in \"$string.\"<hr>"; ?>
The above code replies with:
"stan" occurs 1 time in "substantial."
"a" occurs 2 times in "substantial."
This is the format:
substr_count(STRING,KEY)
STRING is the string to search. KEY is the character sequence to search for.
If STRING is "abacadabra" and KEY is "ab" then substr_count() returns the number 2. Proof:
<?php $string='abacadabra'; $key = "ab"; $value = substr_count($string,$key); echo "<hr>\"$key\" occurs times in \"$string.\"<hr>"; ?>
"ab" occurs 2 times in "abacadabra."
When you need a count of how many times specific characters occur in a string, the PHP substr_count() function is available.
(This content first appeared in Possibilities newsletter.)
Will Bontrager

