Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

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?

like image 469
karthzDIGI Avatar asked Dec 04 '25 00:12

karthzDIGI


1 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];
like image 131
chandresh_cool Avatar answered Dec 06 '25 16:12

chandresh_cool