Search code examples
phparraysregexfiletext-extraction

Parse formatted text and extract two values


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.


Solution

  • Try this:

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