4

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!

Community
  • 1
  • 1
mischa.mole
  • 357
  • 2
  • 12

1 Answers1

4
-?\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);
vks
  • 67,027
  • 10
  • 91
  • 124
  • Thank you, but this gives me 'Warning: preg_match_all(): No ending delimiter '-' found' unfortunately... – mischa.mole Jun 26 '15 at 12:25
  • still not working...test string would be something like "numbers are -3.026 and 5.65 or 6525K" and I'm looking for an array with -3.026, 5.65 and 6525 in it....same thing as the function above in the link does, just with keeping the "-" sign. – mischa.mole Jun 26 '15 at 12:33