3

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?

1
  • 2
    Use regex: preg_match_all('/(?P<digit>\d+(?:\.\d+))(?P<unit>\w+)/', $string, $matches);print_r($matches); Commented Apr 23, 2013 at 8:00

3 Answers 3

8

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];
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @HamZaDzCyberDeV well it was a good workaround though.
Won't match units such as mico grams, for example 5µg
4

Use 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];

Demo

Comments

2

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: %

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.