30

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?

4 Answers 4

61

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.

3
  • 12
    mind you that the third parameter only is optional since 5.4, so to be sure best add a value to receive the matches. see php.net/manual/en/function.preg-match-all.php Jun 13, 2012 at 22:00
  • How can I do if I only want to count many times is repeated the number 4?
    – ras212
    Feb 23, 2017 at 17:08
  • 3
    @ras212 Replace [0-9] with 4.
    – Overv
    Feb 23, 2017 at 17:19
7

first split your string, next filter the result to only include numeric chars and then simply count the resulting elements.

<?php 

$text="12aap33";
print count(array_filter(str_split($text),'is_numeric'));

edit: added a benchmark out of curiosity: (loop of 1000000 of above string and routines)

preg_based.php is overv's preg_match_all solution

harald@Midians_Gate:~$ time php filter_based.php 

real    0m20.147s
user    0m15.545s
sys     0m3.956s

harald@Midians_Gate:~$ time php preg_based.php 

real    0m9.832s
user    0m8.313s
sys     0m1.224s

the regular expression is clearly superior. :)

1
  • Thanks for running the numbers (pun intended) on this one. Aug 3, 2015 at 0:48
4

For PHP < 5.4:

function countDigits( $str )
{
    return count(preg_grep('~^[0-9]$~', str_split($str)));
}
0

This function goes through the given string and checks each character to see if it is numeric. If it is, it increments the number of digits, then returns it at the end.

function countDigits($str) {
    $noDigits=0;
    for ($i=0;$i<strlen($str);$i++) {
        if (is_numeric($str{$i})) $noDigits++;
    }
    return $noDigits;
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.