I have a string variable $nutritionalInfo, this can have values like 100gm, 10mg, 400cal, 2.6Kcal, 10percent etc... I want to parse this string and separate the value and unit part into two variables $value and $unit. Is there any php function available for this? Or how can I do this in php?
Use preg_match_all, like this
$str = "100gm";
preg_match_all('/^(\d+)(\w+)$/', $str, $matches);
var_dump($matches);
$int = $matches[1][0];
$letters = $matches[2][0];
For float value try this
$str = "100.2gm";
preg_match_all('/^(\d+|\d*\.\d+)(\w+)$/', $str, $matches);
var_dump($matches);
$int = $matches[1][0];
$letters = $matches[2][0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With