Reputation: 47
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?
Upvotes: 1
Views: 55
Reputation: 59681
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 )
Upvotes: 2