Reputation: 357
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!
Upvotes: 4
Views: 1684
Reputation: 67968
-?\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);
Upvotes: 4