简体   繁体   English

在preg_match_all中的两个模式之间说一个字

[英]Get a word between two patterns in preg_match_all

I am trying to get the percentage value of download from the following string. 我正在尝试从以下字符串中获取下载的百分比值。

[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

For ex. 对于前。 only the value '100' between '[download]' and '% of' . '100' between '[download]' and '% of'仅取值'100' between '[download]' and '% of' This is my code what I've tried so far 这是到目前为止我尝试过的代码

$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]);
}

But the problem is it grabs from the first line and outputs like 但是问题是它从第一行抓起,输出像

Array ( [0] => Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.mp4 [download] 100 [1] => Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.m4a [download] 100 ) 

If I can grab just before the '% of' that will be okay I think. 我想,如果我能抢在'% of'之前就可以了。 Should I stick to this code for modifying or change the whole pattern? 我应该坚持使用此代码来修改或更改整个模式吗?

This should work for you: 这应该为您工作:

Here I first get your file into an array with file() where every line is one array element. 在这里,我首先使用file()将文件放入数组,其中每一行都是一个数组元素。 There I ignore new line characters and empty lines. 在那里,我忽略了换行符和空行。

After this I go through each line with array_map() where I check with preg_match_all() if there is a pattern like this: [download] (\\d+)% of . 之后,我使用array_map()遍历每一行, array_map()使用preg_match_all()检查是否存在以下模式: [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() out. 如果找到该数字,则返回该数字,否则返回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);

?>

output: 输出:

Array ( [1] => 100 [3] => 100 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM