[英]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)));
我们将字符串分解为单词,然后仅从结果数组中返回数字值并对其进行计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.