如何使用 php 计算字符串中的数字


How to count numbers in a string with php

嗨,我的数据库中有一个这样的动态字符串5,6,7,8,11,25。我想计算字符串中有多少数字。在我的示例中,有 6 个。但我找不到解决方案。请帮助我。

MySQL缺少分解函数,因此您必须使用explode()count()查询数据并在php中进行计数。

count(explode(",", $string));

explode()函数将字符串分解为一个数组元素,每个字符串用逗号分隔,然后count()函数返回该数组中的元素数。

$numbers = explode(',', '5,6,7,8,11,25');
echo count($numbers);

尝试类似

你的字符串

$str = '5,6,7,8,11,25';

然后使用爆炸将字符串转换为数组

$str_array = explode(',', $str);

并获取数组的元素数

$size = count($str_array);

要计算数字,您必须使用如下内容:

count(array_filter(explode(',', $string), "is_numeric"))

但要小心,每个看起来是数字的字符串值都会被计算在内。