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


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

我有一个字符串变量$nutritionalInfo,这可以有100gm, 10mg, 400cal, 2.6Kcal, 10%等值…我想解析这个字符串,把值和单位部分分成两个变量$value$unit。是否有任何php函数可用于此?在php中怎么做呢?

使用preg_match_all,如下所示

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

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