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

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

问题描述:

Let's say in PHP I have a string-variable : "This takes between 5 and 7 days"

I need to store some sensible information about the time it takes in an integer.

I'm satisfied if the result would be 5.

I tried stripping non-numeric characters, but end up with 57 then.

How can this be done in a better way?

让我们说在PHP中我有一个字符串变量:“这需要5到7天” p>

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

如果结果如此,我很满意 5。 p>

我尝试剥离非数字字符,但最终得到57。 p>

如何以更好的方式完成? div>

Use preg_match to match the first digit group using a regex:

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

Using preg_match_all you could match all digit groups (5 and 7 in this example):

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

If you want to quantify the numbers appropriately, I would suggest the following:

<?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;
}

?>

You would need to consider:

  • what happens when no numbers are found, or numbers are given as text instead.
  • what happens when someone says '1 day and 5 hours'

Hopefully this gives you enough information to do the rest yourself.

Seperate the subject into words by splitting the string into an array. Then, somehow I don't know, take the words out of the array. Maybe by looping through all children of the array inside a try-catch block, and try to change each element into an int type:

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

Or something like that. I don't know any of the array methods, but you get what I mean. Anyway, the $words array now only contains numbers.

If you would like to extract the price, ie €7.50 OR $50 etc here is the regular expression comes to the solution for me.

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

results 7.50 OR 50