Extract positive and negative floating point numbers from string in php

For php, I need to extract floating point numbers from a string. I am new to regex but found a solution that works for me in most cases:

Extract floating point numbers from 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 only problem is negative values; can someone change the expression for me in such a way that negative numbers are included correctly as well?

Thank!

+3


source to share


1 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);

      

+3


source







All Articles