phpregexpreg-matchm3u

How to retrieve variable="value" pairs from m3u string


I have m3u file that contain lines like example:

#EXTINF:0 $ExtFilter="Viva" group-title="Variedades" tvg-logo="logo/Viva.png" tvg-name="Viva"

I run this in PHP with no success:

preg_match('/([a-z0-9\-_]+)=\"([a-z0-9\-_\s.]+)\"\s+/i',$str,$matches)

I want to get:

$matches[0] = $ExtFilter
$matches[1] = Viva
$matches[2] = group-title
$matches[3] = Variedades
$matches[4] = tvg-logo
$matches[5] = logo/Viva.png
$matches[6] = tvg-name
$matches[7] = Viva

I try regexp tools (like this).

Thank u.


Solution

  • Use preg_match_all to perform multiple matches:

    preg_match_all('/([\w-]+)="([\w-\s.\/]+)"/i',$str,$matches, PREG_SET_ORDER);
    

    It returns the results as a 2-dimensional array -- one dimension is the match, another dimension is the capture groups within the matches. To get them into a single array as in your desired result, use a loop:

    $results = array();
    foreach ($matches as $match) {
        array_push($results, $match[1], $match[2]);
    }
    print_r($results);
    

    Prints:

    Array
    (
        [0] => ExtFilter
        [1] => Viva
        [2] => group-title
        [3] => Variedades
        [4] => tvg-logo
        [5] => logo/Viva.png
        [6] => tvg-name
        [7] => Viva
    )
    

    I simplified your regexp by using \w in place of a-z0-9_. I also added / to the second character set, so that logo/Viva.png would match. I got rid of \s+ at the end, because it prevented the last variable assignment from working.