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?
3 Answers
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];
2 Comments
chandresh_cool
Thanks @HamZaDzCyberDeV well it was a good workaround though.
mrcendre
Won't match units such as mico grams, for example
5µgUse regexp.
$str = "12Kg";
preg_match_all('/^(\d+|\d*\.\d+)(\w+)$/', $str, $matches);
echo "Value is - ".$value = $matches[1][0];
echo "\nUnit is - ".$month = $matches[2][0];
Comments
I had a similar problem but none of the answers here worked for me. The problem with the other answers is they all assume you'll always have a unit. But sometimes I would have plain numbers like "100" instead of "100kg" and the other solutions would cause the value to be "10" and the units to be "0".
Here's a better solution I somewhat took from this answer. This will separate the number from ANY non-number characters.
$str = '70%';
$values = preg_split('/(?<=[0-9])(?=[^0-9]+)/i', $str);
echo 'Value: ' . $values[0]; // Value: 70
echo '<br/>';
echo 'Units: ' . $values[1]; // Units: %
preg_match_all('/(?P<digit>\d+(?:\.\d+))(?P<unit>\w+)/', $string, $matches);print_r($matches);