【问题标题】:PHP function to separate integer and string part from a given string variablePHP函数将整数和字符串部分与给定的字符串变量分开
【发布时间】:2013-04-23 07:58:38
【问题描述】:

我有一个字符串变量$nutritionalInfo,它的值可以是 100gm、10mg、400cal、2.6Kcal、10percent 等...我想解析这个字符串并将值和单位部分分成两个变量$value$unit。有没有可用的php函数?或者我怎么能在php中做到这一点?

【问题讨论】:

  • 使用正则表达式:preg_match_all('/(?P<digit>\d+(?:\.\d+))(?P<unit>\w+)/', $string, $matches);print_r($matches);

标签: php string


【解决方案1】:

使用 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];

【讨论】:

  • 感谢@HamZaDzCyber​​DeV,不过这是一个很好的解决方法。
  • 与微克等单位不匹配,例如5µg
【解决方案2】:

使用正则表达式。

$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

【讨论】:

  • @HamZaDzCyber​​DeV - 已更新。谢谢兄弟!
【解决方案3】:

我遇到了类似的问题,但这里没有一个答案对我有用。其他答案的问题是他们都假设你总是有一个单位。但有时我会有像“100”这样的普通数字而不是“100kg”,而其他解决方案会导致值为“10”而单位为“0”。

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

$str = '70%';

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

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

【讨论】:

    猜你喜欢
    • 2018-03-26
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 2020-05-18
    相关资源
    最近更新 更多