【问题标题】:How to extract m3u8 of youtube by regex?如何通过正则表达式提取 youtube 的 m3u8?
【发布时间】:2019-10-06 08:54:35
【问题描述】:

我有一个 php 文件已经使用正则表达式从 youtube 中提取 m3u8 链接,直到上周都可以正常工作。

http://server.com/youtube.php?id=youtbueid 像这样传递 youtube id。

$string = get_data('https://www.youtube.com/watch?v=' . $channelid);

if(preg_match('@"hlsManifestUrl.":."(.*?m3u8)@', $string, $match)) {
    $var1=$match[1];
    $var1=str_replace("\/", "/", $var1);
    $man = get_data($var1);
    //echo $man;
    preg_match_all('/(https:\/.*\/95\/.*index.m3u8)/U',$man,$matches, PREG_PATTERN_ORDER);
    $var2=$matches[1][0];
    header("Content-type: application/vnd.apple.mpegurl");
    header("Location: $var2");
}
else {
    preg_match_all('@itag.":([^,]+),."url.":."(.*?).".*?qualityLabel.":."(.*?)p."@', $string, $match);
    //preg_match_all('@itag.":([^,]+),."url.":."(.*?).".*?bitrate.":.([^,]+),@', $string, $match);


    $filter_keys = array_filter($match[3], function($element) {
        return $element <= 720;
    });
    //print_r($filter_keys);

    $max_key = array_keys($filter_keys, max($filter_keys))[0];
    //print_r($max_key);
    $urls = $match[2];
    foreach($urls as &$url) {
        $url = str_replace('\/', '/', $url);
        $url = str_replace('\\\u0026', '&', $url);
    }
    print_r($urls[$max_key]);
    header('location: ' . $urls[$max_key]);

我该如何解决这个问题?

【问题讨论】:

    标签: php regex preg-replace preg-match regex-greedy


    【解决方案1】:

    基于this post,我猜测所需的 URL 可能如下所示:

    我们可以写一个简单的表达式,例如:

    (.+\?v=)(.+)
    

    如果有必要,我们还可以为其添加更多边界。

    正则表达式

    如果不需要此表达式,您可以在regex101.com 中修改/更改您的表达式。

    正则表达式电路

    你也可以在jex.im中可视化你的表情:

    PHP 测试

    $re = '/(.+\?v=)(.+)/m';
    $str = ' https://www.youtube.com/watch?v=_Gtc-GtLlTk';
    $subst = '$2';
    
    $result = preg_replace($re, $subst, $str);
    
    echo $result;
    

    JavaScript 演示

    这个 sn-p 表明我们可能有一个有效的表达式:

    const regex = /(.+\?v=)(.+)/gm;
    const str = ` https://www.youtube.com/watch?v=_Gtc-GtLlTk`;
    const subst = `$2`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, subst);
    
    console.log('Substitution result: ', result);

    【讨论】:

      猜你喜欢
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 2021-12-06
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多