samquo
samquo

Reputation: 757

Counting number of X character

I'm experimenting with something where explode() is failing so I want to try something else. If I have a string, how can I count the number of characters in it that are let's say a comma as in ,

Upvotes: 1

Views: 173

Answers (2)

Try substr_count():

substr_count($text, ',');

Upvotes: 3

Gordon
Gordon

Reputation: 316969

You can use count_chars

Example from PHP Manual:

$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as $i => $val) {
   echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}

Output (codepad):

There were 4 instance(s) of " " in the string.
There were 1 instance(s) of "." in the string.
There were 1 instance(s) of "F" in the string.
There were 2 instance(s) of "T" in the string.
There were 1 instance(s) of "a" in the string.
There were 1 instance(s) of "d" in the string.
There were 1 instance(s) of "e" in the string.
There were 2 instance(s) of "n" in the string.
There were 2 instance(s) of "o" in the string.
There were 1 instance(s) of "s" in the string.
There were 1 instance(s) of "w" in the string.

Upvotes: 1

Related Questions