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?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
This can easily be accomplished with a regular expression.
The function will return the amount of times the pattern was found, which in this case is any digit.
first split your string, next filter the result to only include numeric chars and then simply count the resulting elements.
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
the regular expression is clearly superior. :)
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.
For PHP < 5.4: