How to extract all floating-point numbers from a string of words in PHP

1 Answer

0 votes
/**
 * Extracts all double-precision floating-point numbers containing an explicit
 * decimal point from a given string.
 *
 * @param string $input Source string containing text and numbers.
 * @return float[] Array of extracted floating-point values as floats.
 */
function extractFloats(string $input): array
{
    if (trim($input) === '') {
        return [];
    }

    // Pattern matches numbers containing an explicit decimal point surrounded by digits
    $pattern = '/\b\d+\.\d+\b/';
    
    // Perform regex match to extract all matching sub-strings
    if (preg_match_all($pattern, $input, $matches)) {
        // Convert extracted numerical strings into float values
        return array_map('floatval', $matches[0]);
    }

    return [];
}

// Example input string
$s = "c/c++ c# go 893725.1045 java python 3.14 php 0.0076 javascript";

// Extract floating-point numbers
$numbers = extractFloats($s);

// Display output
echo "Extracted floating-point numbers:\n";
foreach ($numbers as $number) {
    echo $number . "\n";
}



/*
run:

Extracted floating-point numbers:
893725.1045
3.14
0.0076

*/

 



answered Sep 17 by avibootz

Related questions

...