我正在寻找一个可以快速计算字符串中数字字符(即数字)数量的PHP函数。我找不到这样的函数,是否存在这样的函数?
这可以很容易地通过正则表达式实现。
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)));
}
这个函数遍历给定的字符串并检查每个字符是否为数字。如果是数字,它会增加数字的数量,然后在最后返回它。
function countDigits($str) {
$noDigits=0;
for ($i=0;$i<strlen($str);$i++) {
if (is_numeric($str{$i})) $noDigits++;
}
return $noDigits;
}