计数字符串中位数的功能 [英] Function to count number of digits in string

查看:121
本文介绍了计数字符串中位数的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种快速的PHP函数,给定一个字符串,该函数将计算该字符串中数字字符(即数字)的数量.我找不到一个,是否有执行此操作的功能?

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?

推荐答案

可以使用正则表达式轻松实现.

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.

这篇关于计数字符串中位数的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆