D. *_*out 24 php counting digits
我正在寻找一个快速的PHP函数,给定一个字符串,将计算该字符串中的数字字符(即数字)的数量.我找不到一个,有没有这样做的功能?
Ove*_*erv 53
这可以通过正则表达式轻松完成.
function countDigits( $str )
{
    return preg_match_all( "/[0-9]/", $str );
}
该函数将返回找到模式的次数,在本例中为任何数字.
首先拆分你的字符串,然后过滤结果只包含数字字符,然后简单地计算结果元素.
<?php 
$text="12aap33";
print count(array_filter(str_split($text),'is_numeric'));
编辑:出于好奇心添加了一个基准:(上述字符串和例程的1000000循环)
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
正则表达明显优越.:)
对于PHP <5.4:
function countDigits( $str )
{
    return count(preg_grep('~^[0-9]$~', str_split($str)));
}