Extract floating point numbers from a delimited string in PHP

$str="152.15 x 12.34 x 11mm";
preg_match_all('!\d+(?:\.\d+)?!', $str, $matches);
$floats = array_map('floatval', $matches[0]);
print_r($floats);

The (?:...) regular expression construction is what’s called a non-capturing group. What that means is that chunk isn’t separately returned in part of the $mathces array. This isn’t strictly necessary in this case but is a useful construction to know.

Note: calling floatval() on the elements isn’t strictly necessary either as PHP will generally juggle the types correctly if you try and use them in an arithmetic operation or similar. It doesn’t hurt though, particularly for only being a one liner.

Leave a Comment