Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to count number of digits in string

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?

like image 642
Ashley Strout Avatar asked Jun 13 '12 21:06

Ashley Strout


People also ask

Does count () work on strings?

Python String count() MethodThe count() method returns the number of times a specified value appears in the string.


1 Answers

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.

like image 146
Overv Avatar answered Sep 20 '22 20:09

Overv