PHP:如何计算数字


PHP: how to count numbers?

如何使用php 计数

$mynumbers="0855 468 4864 63848 1486"; //This is my variable, the pattern has to be like this, each number is separated by a space.
echo "There are 5 numbers in your variable";

它应该返回:5

我该怎么做,我知道有str_word_count,但它只计算单词而不计算数字。

这应该适用于您:

$str = "0855 468 4864 63848 1486";
preg_match_all("/'d+/", $str, $matches);
echo count($matches[0]);

输出:

5

您可以尝试explode()函数,如下所示:

$mynumbers="0855 468 4864 63848 1486";
$values = explode(" ", $mynumbers);
echo count($values);

希望它能帮助

例如使用explode()

$mynumbers = "0855 468 4864 63848 1486";
$exploded = explode(' ', $mynumbers); 
echo 'There are '.count($exploded).' numbers in your variable.';

简单的单线分辨率:

$numCount = count(array_map(function($value){return is_numeric($value);}, explode(' ', $mynumbers)));

我们将字符串导出为单词,然后只返回结果数组中的数值并对其进行计数。