【问题标题】:PHP: how to get numeric value of a string with multiple numbers?PHP:如何获取具有多个数字的字符串的数值?
【发布时间】:2012-06-19 23:35:58
【问题描述】:

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

我需要以整数形式存储一些有关所需时间的合理信息。

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

我尝试去除非数字字符,但结果是 57。

如何以更好的方式做到这一点?

【问题讨论】:

    标签: php string type-conversion


    【解决方案1】:

    使用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,您可以匹配所有数字组(本例中为5 和7):

    $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';
    }
    

    【讨论】:

    • /\d+/ 可能会更好,如果可以使用多于一位的数字。
    【解决方案2】:

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

    <?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 小时”时会发生什么

    希望这可以为您提供足够的信息,让您自己完成剩下的工作。

    【讨论】:

      【解决方案3】:

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

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

      结果 7.50 或 50

      【讨论】:

        【解决方案4】:

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

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

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

        【讨论】:

        • 首先,这种方法行不通。如果字符串不包含数字,您假设将字符串转换为整数(通过使用(int) $string)会引发异常。此外,这样的方法并不是一个优雅的解决方案:您可以使用正则表达式来做得更好。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-27
        • 1970-01-01
        • 2020-01-25
        • 2023-01-17
        • 2022-10-15
        • 1970-01-01
        • 2011-12-22
        相关资源
        最近更新 更多