duanbixia7738 2017-05-01 15:43
浏览 158
已采纳

如何从字符串中获取数字/浮点数

I want to get the (first) price of each string row, with out the $ sign and it could be an int or float and there could be more numbers in the row.

example:

$str_array=(
"Up to $1.9 per Install in RU",
"1.3 per iOS Install in UAE and SA",
"$2.1 per iOS and Android Registration in US",
"Up to $2.5 per Android Install in 7 countries",
"Up to $1 per iOS Install in SA"
);

Expected output:

1.9
1.3
2.1
2.5
1

I tried something like this

$re = '/[+-]?([0-9]*[.])?[0-9]+/';
$str = 'Up to $2.5 per Android Install in 7 countries';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);   

and i get this

[0] => Array
    (
        [0] => 2.5
        [1] => 2.
    )

[1] => Array
    (
        [0] => 7
    )

but its not working good. :(

  • 写回答

3条回答 默认 最新

  • duanmeng7865 2017-05-01 15:54
    关注

    Here is my version:

    <?php
    $data = [
        'Up to $1.9 per Install in RU',
        '1.3 per iOS Install in UAE and SA',
        '$2.1 per iOS and Android Registration in US',
        'Up to $2.5 per Android Install in 7 countries',
        'Up to $1 per iOS Install in SA'
    ];
    
    array_walk($data, function(&$line){
        preg_match('/(\d+(?:\.\d+)?)/', $line, $tokens);
        if (count($tokens)>1) {
            var_dump(floatval($tokens[1]));
        }
    });
    

    The output obviously is:

    float(1.9)
    float(1.3)
    float(2.1)
    float(2.5)
    float(1)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料