Extract floating point numbers from a string in PHP

前端 未结 5 1885
盖世英雄少女心
盖世英雄少女心 2020-12-02 00:22

I would like to convert a string into floating numbers. For example

152.15 x 12.34 x 11mm

into

152.15, 12.34 and 11
         


        
相关标签:
5条回答
  • 2020-12-02 00:45
    preg_match_all("/\d*\.?\d+|\d+/", "152.15mmx12.34mm x .11mm", $matches);
    

    This example supports numbers like .11 as well, since they are valid numbers. $matches[0] will contain 152.15, 12.34 and 0.11, given that you type cast the result to float. If you don't 0.11 will appear as .11. I would type cast using array_map.

    $values = array_map("floatval", $matches[0]); 
    

    You can use the values for anything math without type casting them though. casting is just needed when printing them directly.

    0 讨论(0)
  • 2020-12-02 00:53
    $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 (?:...) regular expression construction is what's called a non-capturing group. What that means is that chunk isn't separately returned in part of the $mathces array. This isn't strictly necessary in this case but is a useful construction to know.

    Note: calling floatval() on the elements isn't strictly necessary either as PHP will generally juggle the types correctly if you try and use them in an arithmetic operation or similar. It doesn't hurt though, particularly for only being a one liner.

    0 讨论(0)
  • 2020-12-02 00:57
    <?php
    
    $s = "152.15 x 12.34 x 11mm";
    
    if (preg_match_all('/\d+(\.\d+)?/', $s, $matches)) {
        $dim = $matches[0];
    }
    
    print_r($dim);
    
    ?>
    

    gives

    Array
    (
        [0] => 152.15
        [1] => 12.34
        [2] => 11
    )
    
    0 讨论(0)
  • 2020-12-02 00:59
    $string = '152.15 x 12.34 x 11mm';
    preg_match_all('/(\d+(\.\d+)?)/', $string, $matches);
    print_r($matches[0]); // Array ( [0] => 152.15 [1] => 12.34 [2] => 11 ) 
    
    0 讨论(0)
  • 2020-12-02 01:00
    $str = "152.15 x 12.34 x 11mm";
    $str = str_replace("mm", "", $str);
    $str = explode("x", $str);
    print_r($str); // Array ( [0] => 152.15 [1] => 12.34 [2] => 11 ) 
    

    Tested it and it works on all strings above.

    0 讨论(0)
提交回复
热议问题