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 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法