繁体   English   中英

PHP:如何获取具有多个数字的字符串的数值?

[英]PHP: how to get numeric value of a string with multiple numbers?

让我们说在PHP中我有一个字符串变量: "This takes between 5 and 7 days"

我需要存储一些关于整数所需时间的合理信息。

如果结果是5,我很满意。

我尝试剥离非数字字符,但结果是57然后。

如何以更好的方式完成?

使用preg_match使用正则表达式匹配第一个数字组:

$subject = 'This takes between 5 and 7 days';
if (preg_match('/\d+/', $subject, $matches)) {
    echo 'First number is: ' . $matches[0];
} else {
    echo 'No number found';
}

使用preg_match_all可以匹配所有数字组(本例中为57 ):

$subject = 'This takes between 5 and 7 days';
if (preg_match_all('/\d+/', $subject, $matches)) {
    echo 'Matches found:<br />';
    print_r($matches);
} else {
    echo 'No number found';
}

如果你想适当地量化数字,我建议如下:

<?php
$subject = "This takes between 5 and 7 days";

$dayspattern = '/\d+(\.\d+)? ?days?/';
$hourspattern = '/\d+(\.\d+)? ?hours?/'

$hours = -1;

if (preg_match($dayspattern , $subject, $matches) > 0)
{
  preg_match($dayspattern, $matches[0], $days);
  $hours = $days * 24;
} elseif (preg_match($dayspattern , $subject, $matches) > 0) {
  preg_match($hourspattern, $matches[0], $hours);
  $hours = $hours;
}

?>

你需要考虑:

  • 当没有找到数字时会发生什么,或者数字是作为文本给出的。
  • 当有人说“1天5小时”时会发生什么

希望这能为您提供足够的信息来自己完成剩下的工作。

如果你想提取价格,即7.50欧元或50美元等,这里正则表达式为我提供解决方案。

 preg_match('/\d+\.?\d*/',$price_str,$matches); 
 echo $matches[0]; 

结果7.50或50

通过将字符串拆分为数组将主题分隔为单词。 然后,不知怎的,我不知道,从阵列中取出的话。 也许通过循环遍历try-catch块中的所有数组子节点,并尝试将每个元素更改为int类型:

for($i=0;$i<$words->length;$i++){
    try{
        $tempNum = (int)$words[$i];
    }catch($ex){
        $words->remove($i);
    }
}

或类似的东西。 我不知道任何数组方法,但你明白我的意思。 无论如何, $words数组现在只包含数字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM