dongyata3336 2017-03-29 11:50
浏览 59
已采纳

计算字符串中出现的数字数量

I was wondering if there's a combo of functions or a direct function that can count how many numbers appears in a string, without use a long-way as str_split and check every character in a loop.

From a string like:

fdsji2092mds1039m

It returns that there's 8 numbers inside.

  • 写回答

4条回答 默认 最新

  • doujia2463 2017-03-29 11:54
    关注

    You can use filter_var() with the FILTER_SANITIZE_NUMBER_INT constant, then check the length of the new string. The new string will contain only numbers from that string, and all other characters are filtered away.

    $string = "j3987snmj3j";
    $numbers = filter_var($string , FILTER_SANITIZE_NUMBER_INT);
    $length = strlen($numbers); // 5
    echo "There are ".$length." numbers in that string";
    

    Note that each number will be counted individually, so 137 would return 3, as would 1m3j7.

    Live demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭