php 计算字符串中位数的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11023753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Function to count number of digits in string
提问by D. Strout
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?
我正在寻找一个快速的 PHP 函数,给定一个字符串,它会计算该字符串中数字字符(即数字)的数量。我找不到,有什么功能可以做到这一点?
回答by Overv
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.
该函数将返回找到模式的次数,在这种情况下是任何数字。
回答by Harald Brinkhof
first split your string, next filterthe result to only include numericchars and then simply countthe 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)
编辑:出于好奇添加了一个基准测试:(上述字符串和例程的 1000000 个循环)
preg_based.php is overv's preg_match_all solution
preg_based.php 是 overv 的 preg_match_all 解决方案
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. :)
正则表达式显然更胜一筹。:)
回答by Alix Axel
For PHP < 5.4:
对于 PHP < 5.4:
function countDigits( $str )
{
return count(preg_grep('~^[0-9]$~', str_split($str)));
}
回答by D. Strout
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;
}

