Extract positive and negative floating point numbers from a string in php

1.6k views Asked by At

For a php I have to extract floating point numbers from a string. I'm new to regex, but I found a solution which works for me in most cases:

Extract floating point numbers from a 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);

Only problem are negative values; can somebody change the expression for me in a way that negative numbers are also included properly?

Thanks!

1

There are 1 answers

2
vks On BEST ANSWER
-?\d+(?:\.\d+)?

This should do it for you.

$re = "/-?\\d+(?:\\.\\d+)?/m"; 
$str = "4.321 -3.1212"; 
$subst = "coach"; 

$result = preg_replace($re, $subst, $str);