KarthzDIGI KarthzDIGI - 3 years ago 160
PHP Question

PHP function to separate integer and string part from a given string variable

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?

Answer Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download