使用php获取intval()?
假设我有以下字符串:使用php获取intval()?,php,function,integer,Php,Function,Integer,假设我有以下字符串: danger13 afno 1 900004 使用intval()它给了我13,但是,我想获取字符串中的最高整数,即9000004,如何实现这一点 编辑:字符串有不同的形式,我不知道最大的数字在哪里。您需要从字符串中获取所有整数,然后找到最大的 $str = "danger13 afno 1 900004"; preg_match_all('/\d+/', $str, $matches); // get all the number-only patterns $numb
danger13 afno 1 900004
使用intval()
它给了我13,但是,我想获取字符串中的最高整数,即9000004,如何实现这一点
编辑:字符串有不同的形式,我不知道最大的数字在哪里。您需要从字符串中获取所有整数,然后找到最大的
$str = "danger13 afno 1 900004";
preg_match_all('/\d+/', $str, $matches); // get all the number-only patterns
$numbers = $matches[0];
$numbers = array_map('intval', $numbers); // convert them to integers from string
$max = max($numbers); // get the largest
$max
现在是900004
请注意,这非常简单。如果字符串中有任何内容与模式\d+
(1个或多个数字)相匹配,而您不希望将其作为单独的整数进行匹配(例如,43.535
将返回535
),则您不会满意。您需要更详细地定义您的意思。
<?php
$string = 'danger13 afno 1 900004';
preg_match_all('/[\d]+/', $string, $matches);
echo '<pre>'.print_r($matches,1).'</pre>';
$highest = array_shift($matches[0]);
foreach($matches[0] as $v) {
if ($highest < $v) {
$highest = $v;
}
}
echo $highest;
?>
ETA:已更新以允许以数字结尾或包含数字的“单词”(感谢Gordon!)对于字符串中的词典最高整数值(最多
PHP\u INT\u MAX
),您可以将数字拆分并获得最大值:
$digitsList = preg_split('/[^\d]+/', $str, NULL, PREG_SPLIT_NO_EMPTY);
if (!$digitsList)
{
throw new RuntimeException(sprintf('Unexpected state; string "%s" has no digits.', $str));
}
$max = max($digitsList);
或更好的自我记录:
想到的一种方法是使用
explode()
将字符串拆分为数组,遍历每个成员,找到最高的一个。字符串是否总是具有相同的格式?您想要字符串中的“最高数字”还是始终是字符串中的最后一个数字?intval('danger13 afno 1 900004')
不会给出13
@Gordon:point takepreg_split
并过滤掉Alpha,然后max才能更好地工作。
$max = max(preg_split('/[^\d]+/', $str, NULL, PREG_SPLIT_NO_EMPTY));
$digitsList = preg_split('/[^\d]+/', $str, NULL, PREG_SPLIT_NO_EMPTY);
if (!$digitsList)
{
throw new RuntimeException(sprintf('Unexpected state; string "%s" has no digits.', $str));
}
$max = max($digitsList);