在 preg_match_all 中获取两个模式之间的单词
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'
。
这是我到目前为止尝试过的代码
$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()
where I check with preg_match_all()
if there is a pattern like this: [download] (\d+)% of
. If it finds the number I return it otherwise I return false and at the end I filter the elements with false with array_filter()
。
<?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 )
我正在尝试从以下字符串中获取下载的百分比值。
[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'
。
这是我到目前为止尝试过的代码
$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()
where I check with preg_match_all()
if there is a pattern like this: [download] (\d+)% of
. If it finds the number I return it otherwise I return false and at the end I filter the elements with false with array_filter()
。
<?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 )