Function to count number of digits in string

D. Strout picture D. Strout · Jun 13, 2012 · Viewed 30.3k times · Source

I was looking for a quick PHP function that, given a string, would count the number of numerical characters (i.e. digits) in that string. I couldn't find one, is there a function to do this?

Answer

Overv picture Overv · Jun 13, 2012

This can easily be accomplished with a regular expression.

function countDigits( $str )
{
    return preg_match_all( "/[0-9]/", $str );
}

The function will return the amount of times the pattern was found, which in this case is any digit.