简体   繁体   中英

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' . 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. 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. 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 . 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.

<?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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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