我有一个字符串变量$nutritionalInfo
,它的值可以是100gm、10mg、400cal、2.6Kcal、10percent等...我想解析这个字符串并将值和单位部分分开分为两个变量 $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];
对于浮点值试试这个
$str = "100.2gm";
preg_match_all('/^(\d+|\d*\.\d+)(\w+)$/', $str, $matches);
var_dump($matches);
$int = $matches[1][0];
$letters = $matches[2][0];
关于PHP函数从给定的字符串变量中分离整数和字符串部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16163988/