views:

69

answers:

2
+1  Q: 

Regex on an array?

Hi

How do I get the percentage and filesize from this sort of string using regex in PHP?

The thing is I get this string using the print_r function like so:

while(!feof($handle))
{
    $progress = fread($handle, 8192);
    print_r($progress); 
}

The above outputs something like this:

    [download] 28.8% of 1.51M at 171.30k/s ETA 00:06

I'm sure I need to use something like preg_match but not sure how to do it for an array plus how do I reference the string. The regex needs to be placed inside the loop.

Thanks for any help.

+1  A: 
$string = '[download] 28.8% of 1.51M at 171.30k/s ETA 00:06
           [download] 41.8% of 1.51M at 178.19k/s ETA 00:05';

// $string = file_get_contents($file_path);

$pattern = '/(?<percent>[0-9]{1,2}\.[0-9]{1,2})% of (?<filesize>.+) at/';
preg_match_all($pattern, $string, $matches);

print_r($matches);
Ionuț G. Stan
What happens at 100%?
Nerdling
Good question, Nerdling.
Gumbo
(?<percent>\d{1,3}(?:\.\d{0,2})?)%
OIS
I managed to change that. How can I remove the word "at"?
Abs
For some reason I thought I was dealing with time units, where for example 09:60 is actually 10:00
Ionuț G. Stan
+2  A: 

Try this:

foreach ($progress as $str) {
    if (preg_match_all('/\[download] (\d+\.\d)% of (\d+\.\d+\w)/', $str, $matches)) {
        var_dump($matches);
    }
}
Gumbo