PHP函数从给定字符串变量中分离整数和字符串部分

PHP函数从给定字符串变量中分离整数和字符串部分,php,string,Php,String,我有一个字符串变量$nutritionalInfo,它可以有100gm、10mg、400cal、2.6Kcal、10%等值。。。我想解析这个字符串,并将值和单位部分分成两个变量$value和$unit。是否有任何php函数可用于此?或者如何在php中实现这一点 像这样使用preg\u match\u all $str = "100gm"; preg_match_all('/^(\d+)(\w+)$/', $str, $matches); var_dump($matches); $int =

我有一个字符串变量
$nutritionalInfo
,它可以有100gm、10mg、400cal、2.6Kcal、10%等值。。。我想解析这个字符串,并将值和单位部分分成两个变量
$value
$unit
。是否有任何php函数可用于此?或者如何在php中实现这一点

像这样使用preg\u match\u all

$str = "100gm";
preg_match_all('/^(\d+)(\w+)$/', $str, $matches);

var_dump($matches);

$int = $matches[1][0];
$letters = $matches[2][0];
对于浮点值,请尝试以下方法

$str = "100.2gm";
preg_match_all('/^(\d+|\d*\.\d+)(\w+)$/', $str, $matches);

var_dump($matches);

$int = $matches[1][0];
$letters = $matches[2][0];
使用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];

我也有类似的问题,但这里的答案都不适合我。其他答案的问题是它们都假设你总是有一个单位。但有时我会用“100”而不是“100kg”这样的简单数字,而其他解决方案会导致值为“10”,单位为“0”

我从中得到了一个更好的解决方案。这会将数字与任何非数字字符分开

$str = '70%';

$values = preg_split('/(?<=[0-9])(?=[^0-9]+)/i', $str);

echo 'Value: ' . $values[0]; // Value: 70
echo '<br/>';
echo 'Units: ' . $values[1]; // Units: %
$str='70%';

$values=preg\u split('/(?使用regex:
preg\u match\u all('/(?P\d+(?:\.\d+)(?P\w+)/,$string,$matches);print\u r($matches);
谢谢@HamZaDzCyberDeV这是一个很好的解决方法。不会匹配mico grams等单位,例如
5µg
@HamZaDzCyberDeV-更新。谢谢兄弟!