考虑如下字符串。
$string="Lorem ipsum $ 1000 ,ipsum $2000 sopr $250 gerb $ 150 dfkuer fsdf erwer 1020 $ gsdfasdtwe qw $ 5000 efk kdfgksgdf 2000 $ sdhfgsd fsdf 620 $ sdfjg jsdf3000$";
我必须找出这个字符串中有多少个数字。但是这个数字等于1000且高于1000,然后是$符号。
示例:1000美元(或)1000美元(或)1000美元(或)1000美元以上仅1000美元。
答案 0 :(得分:1)
使用preg_match_all()和foreach循环:
$string="Lorem ipsum $ 1000 ,ipsum $2000 sopr $250 gerb $ 150 dfkuer fsdf erwer 1020 $ gsdfasdtwe qw $ 50000 efk kdfgksgdf 2000 $ sdhfgsd fsdf 620 $ sdfjg jsdf3000$";
preg_match_all('/(\$\s?)(?P<before>\d{4,})|(?P<after>\d{4,})(\s?\$)/', $string, $m);
$tmp = array_filter($m["before"]) + array_filter($m["after"]);
$number = array();
foreach($tmp as $n){
if($n >= 1000){
if(isset($number[$n])){
$number[$n]++;
}else{
$number[$n] = 1;
}
}
}
print_r($number);
// Key => number, value => n occurences
我已使用\d{4,}
来匹配1000位或更高位的4位数字,但比方说有一个像0500
这样的数字,这也将匹配。所以我用foreach循环来过滤数字。
答案 1 :(得分:0)
<?php
$string="Lorem ipsum $ 1000 ,ipsum $2000 sopr $250 gerb $ 150 dfkuer fsdf erwer 1020 $ gsdfasdtwe qw $ 5000 efk kdfgksgdf 2000 $ sdhfgsd fsdf 620 $ sdfjg jsdf3000$";
$pattern = "#([$][\s]*)?([1-9]\d{3})([\s]*[$])?#";
//(?<=$|$\s)
//(?=$|\s$)
preg_match_all($pattern, $string, $out);
print_r($out[2]);
Array
(
[0] => 1000
[1] => 2000
[2] => 1020
[3] => 5000
[4] => 2000
[5] => 3000
)
答案 2 :(得分:0)
试试这个:
$string ="Lorem ipsum $ 1000 ,ipsum $2000 sopr $250 gerb $ 150 dfkuer fsdf erwer 1020 $ gsdfasdtwe qw $ 5000 efk kdfgksgdf 2000 $ sdhfgsd fsdf 620 $ sdfjg jsdf3000$";
preg_match_all('/\$\s?(?P<pr>\d{4,})|(?P<fl>\d{4,})\s?\$/',$string,$match);
$res = array_merge(array_filter($match['pr']),array_filter($match['fl']));
echo "<pre>";
print_r($res);
输出:
Array
(
[0] => 1000
[1] => 2000
[2] => 5000
[3] => 1020
[4] => 2000
[5] => 3000
)