How to retrieve variable=“value” pairs from m3u string

≯℡__Kan透↙ 提交于 2020-02-16 08:26:00

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/26833575/how-to-retrieve-variable-value-pairs-from-m3u-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!