[英]Get content between two words - preg_match_all multiple patterns
[英]Get a word between two patterns in preg_match_all
我正在尝试从以下字符串中获取下载的百分比值。
[download] Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.mp4
[download] 100% of 1.60MiB in 00:21
[download] Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.m4a
[download] 100% of 164.86KiB in 00:01
对于前。 '100' between '[download]' and '% of'
仅取值'100' between '[download]' and '% of'
。 这是到目前为止我尝试过的代码
$file = file_get_contents("t.txt");
if (preg_match_all("/(?<=\[download\])(.*?)(?=\% of)/s", $file, $result))
for ($i = 1; count($result) > $i; $i++) {
print_r($result[$i]);
}
但是问题是它从第一行抓起,输出像
Array ( [0] => Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.mp4 [download] 100 [1] => Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.m4a [download] 100 )
我想,如果我能抢在'% of'
之前就可以了。 我应该坚持使用此代码来修改或更改整个模式吗?
这应该为您工作:
在这里,我首先使用file()
将文件放入数组,其中每一行都是一个数组元素。 在那里,我忽略了换行符和空行。
之后,我使用array_map()
遍历每一行, array_map()
使用preg_match_all()
检查是否存在以下模式: [download] (\\d+)% of
。 如果找到该数字,则返回该数字,否则返回false,最后使用array_filter()
过滤出具有false的元素。
<?php
$lines = file("t.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$numbers = array_filter(array_map(function($v){
if(preg_match_all("/\[download\] (\d+)% of/", $v, $m))
return $m[1][0];
else
return false;
}, $lines));
print_r($numbers);
?>
输出:
Array ( [1] => 100 [3] => 100 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.