PHP:如何统计数字?

时间:2015-02-23 10:34:09

标签: php count

如何使用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但它只计算单词而非数字。

4 个答案:

答案 0 :(得分:3)

这应该适合你:

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

输出:

5

答案 1 :(得分:2)

您可以尝试使用explode()功能:

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

希望有所帮助

答案 2 :(得分:2)

例如使用explode()

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

答案 3 :(得分:0)

简单的单行分辨率:

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

我们将字符串扩展为单词,然后仅返回结果数组中的数值并计算它们。