简体   繁体   中英

preg_grep does not return the right results

The following code does not capture 45.00 as a result:

$array = array(50,45.00,34,56,6.67);
$fl_array = preg_grep("/^(\d+)?\.(\d)+$/", $array);

Any suggestion?

If you do a var_dump($array); you will get:

array(5) {
  [0]=> int(50)
  [1]=> float(45)
  [2]=> int(34)
  [3]=> int(56)
  [4]=> float(6.67)
}

PHP you transform 45.00 into 45 . That's why you can't find with the regex.

What you can do is to insert only strings.

$array = array("50","45.00","34","56","6.67");

Then it's going to work.

Another option is to filter only float numbers from the array:

$array = array(50,45.00,34,56,6.67);
$fl_array = array_filter($array, function($item) {
    return is_float($item);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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