What is the most efficient way to count all the occurrences of a specific character in a PHP string?
If you are going to be repeatedly checking the same string, it'd be smart to have some sort of trie or even assoc array for it otherwise, the straightforward way to do it is...
for($i = 0; $i < strlen($s); $i++)
if($s[i] == $c)
echo "{$s[i]} at position $i";
Can you not feed the character to preg_match_all?
Not sure what kind of a response you're looking for, but here's a function that might do it:
function findChar($c, $str) {
indexes = array();
for($i=0; $i<strlen($str); $i++) {
if ($str{$i}==$c) $indexes[] = $i;
}
return $indexes;
}
Pass it the character you're looking for and the string you want to look:
$mystring = "She shells out C# code on the sea shore";
$mychar = "s";
$myindexes = $findChar($mychar, $mystring);
print_r($myindexes);
It should give you something like
Array (
[0] => 0
[1] => 4
[2] => 9
[3] => 31
[4] => 35
)
or something...
use this:
echo substr_count("abca", "a"); // will echo 2