-2

I am trying to count how many times number appears in a string. For example, in the string "rt_876_io_542_po_367" there are three numbers and in the string "tr_766_ 756" there are two numbers. How do I do this with PHP?? I tried the following code:

        $str="RT_657_YT_89";
        $key=preg_match_all('!/_[0-9]_/!',$str);
        echo $key;

but it echos "0"!! please help

Ankur Choudhury
  • 189
  • 2
  • 13

1 Answers1

1

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.

ThomasVdBerge
  • 7,483
  • 4
  • 44
  • 62