fork download
  1. <?php
  2.  
  3. $data = 'Weight 229.6104534866 g
  4. Energy 374.79170898476 kcal
  5. Total lipid (fat) 22.163422468932 g
  6. Carbohydrate, by difference 13.641848209743 g
  7. Sugars, total 4.3691034101428 g
  8. Protein 29.256342349938 g
  9. Sodium, Na 468.99386390008 mg ';
  10.  
  11. $pattern = '~^(?P<category>\D+)\s+(?P<value>[\d.]+)\s+(?P<unit>.+)~m';
  12.  
  13. preg_match_all($pattern, $data, $matches, PREG_SET_ORDER, 0);
  14.  
  15. // Print the entire match result
  16. print_r($matches);
  17. ?>
Success #stdin #stdout 0.02s 25864KB
stdin
Standard input is empty
stdout
Array
(
    [0] => Array
        (
            [0] => Weight 229.6104534866 g
            [category] => Weight
            [1] => Weight
            [value] => 229.6104534866
            [2] => 229.6104534866
            [unit] => g
            [3] => g
        )

    [1] => Array
        (
            [0] => Energy 374.79170898476 kcal
            [category] => Energy
            [1] => Energy
            [value] => 374.79170898476
            [2] => 374.79170898476
            [unit] => kcal
            [3] => kcal
        )

    [2] => Array
        (
            [0] => Total lipid (fat) 22.163422468932 g
            [category] => Total lipid (fat)
            [1] => Total lipid (fat)
            [value] => 22.163422468932
            [2] => 22.163422468932
            [unit] => g
            [3] => g
        )

    [3] => Array
        (
            [0] => Carbohydrate, by difference 13.641848209743 g
            [category] => Carbohydrate, by difference
            [1] => Carbohydrate, by difference
            [value] => 13.641848209743
            [2] => 13.641848209743
            [unit] => g
            [3] => g
        )

    [4] => Array
        (
            [0] => Sugars, total 4.3691034101428 g
            [category] => Sugars, total
            [1] => Sugars, total
            [value] => 4.3691034101428
            [2] => 4.3691034101428
            [unit] => g
            [3] => g
        )

    [5] => Array
        (
            [0] => Protein 29.256342349938 g
            [category] => Protein
            [1] => Protein
            [value] => 29.256342349938
            [2] => 29.256342349938
            [unit] => g
            [3] => g
        )

    [6] => Array
        (
            [0] => Sodium, Na 468.99386390008 mg 
            [category] => Sodium, Na
            [1] => Sodium, Na
            [value] => 468.99386390008
            [2] => 468.99386390008
            [unit] => mg 
            [3] => mg 
        )

)