Extract floating point numbers from a string in PHP

前端 未结 5 1951
盖世英雄少女心
盖世英雄少女心 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.

提交回复
热议问题