Click to See Complete Forum and Search --> : counting repeating characters


moiseszaragoza
11-29-2007, 10:22 AM
Is there any way that PHP knows how many times a specific character appears on a string?

sstalder
11-29-2007, 12:33 PM
Here is a quick little function that should do the trick.

<?PHP
function countChar($string,$c)
{
$numChars = preg_match_all("/$c/", $string, $num);
return count($num[0]);
}

$string = "This is a test to count chars in this string aa bbb cccc eeeeeee fffffff";
echo "<b>String:</b> $string<br />";
echo "There are 4 matches for " . countChar($string,"a") . "the letter 'a'.";
?>

NogDog
11-29-2007, 01:09 PM
PHP has a count_chars (http://www.php.net/manual/en/function.count-chars.php)() function.

masterkey
11-29-2007, 01:43 PM
I would just do something like this:

<?php
function countchar($c, $str) {
return strlen(preg_replace("/[^$c]/", '', $str));
}
?>

delete anything except the char in the string and returns the length of the resulting string

sstalder, with your function I think you could just do return preg_match_all("/$c/", $string, $nothing) and skip the call to count(), preg_match_all() already returns the number of matches

NogDog
11-29-2007, 02:17 PM
If you are going to throw any supplied string into a preg_* regexp, I'd suggest filtering it through preg_quote (http://www.php.net/preg_quote)() first.