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";

应该return: 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)));

我们将字符串分解成单词,然后 return 仅从结果数组中提取数值并对它们进行计数。