How to extract a float from a string in PHP

1 Answer

0 votes
$text = "The price is 148.95 dollars";

$floatRegex = '/[-+]?\d*\.\d+|\d+/';

if (preg_match($floatRegex, $text, $matches)) {
    $number = floatval($matches[0]);
    echo "Extracted float: " . $number;
}



/*
run:

Extracted float: 148.95

*/

 



answered Jul 29, 2025 by avibootz
...