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

标签 php string

我有一个字符串变量$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/

相关文章:

php - 代表四个条件对 Laravel 集合进行排序

java - 切换大小写不返回字符串

java - 没有获得线程程序的预期输出

c++ - string::compare 确定字母顺序是否可靠?

php - mysql 使用 IF NOT IN 关键字或替代方法选择所有其他数据

php - 当购物车商品具有特定运输类别时禁用运输方式?

c++ - 井字游戏代码失败

Java按第三列的数值对二维字符串数组进行排序

php - 如何在不更改文件夹的情况下更改网址?

php - 在 Eloquent 中为每个模型附加关系计数