我希望获得每个字符串行的(第一个)价格,而不是$符号,它可以是一个int或float,并且行中可能有更多数字。
示例:
$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"
);
预期输出:
1.9
1.3
2.1
2.5
1
我试过这样的事情
$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);
我得到了这个
[0] => Array
(
[0] => 2.5
[1] => 2.
)
[1] => Array
(
[0] => 7
)
但它不能正常工作。 :(
答案 0 :(得分:1)
这是我的版本:
<?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]));
}
});
输出显然是:
float(1.9)
float(1.3)
float(2.1)
float(2.5)
float(1)
答案 1 :(得分:0)
希望这会帮助你,
正则表达式: \d+(?:\.\d+)?
1。
\d+
这将匹配数字2。
(?:\.\d+)?
这可选择匹配小数部分
<?php
ini_set('display_errors', 1);
$str_array=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"
);
$result=array();
foreach($str_array as $string)
{
preg_match_all('/[\d]+(?:\.[\d]+)?/',$string,$matches);
$result[]=$matches[0][0];
}
print_r($result);
<强>输出:强>
Array
(
[0] => 1.9
[1] => 1.3
[2] => 2.1
[3] => 2.5
[4] => 1
)
答案 2 :(得分:0)