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

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

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. :(

图片转代码服务由CSDN问答提供 功能建议

我想得到每个字符串行的(第一个)价格,没有$符号,它可能是一个 int或float,行中可能有更多数字。

示例:

  $ str_array =(
“RU中每次安装最多1.9美元”,
“每个iOS安装1.3个 在阿联酋和SA“,
”每个iOS 2.1美元和美国Android注册“,
”在7个国家/地区每个Android安装最高2.5美元“,
”每个iOS安装在SA中最多1美元“
); \  n   
 
 

预期输出:

  1.9 
1.3 
2.1 \  n2.5 
1 
   
 
 

我尝试过这样的事情

  $ re ='/ [+  - ]  ?([0-9] * [。])?[0-9] + /'; 
 $ str ='7个国家/地区的每个Android安装最高2.5美元'; 
 npreg_match_all($ re,$ str,$ match  ,PREG_SET_ORDER,0); 
var_dump($ matches);  
   
 
 

我得到了这个

  [0] => 数组
(
 [0] => 2.5 
 [1] => 2. 
)
 
 [1] => 数组
(
 [0] => 7 
)
   
 
 

但它不能正常工作。 :(

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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条)

相关推荐 更多相似问题