1

I had a php file already using regex to extract m3u8 link from youtube, which was working fine until last week.

http://server.com/youtube.php?id=youtbueid use to pass the youtube id like this.

$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]);

How do I solve this problem?

Emma
  • 27,428
  • 11
  • 44
  • 69

1 Answers1

3

Based on this post, I'm guessing that the desired URLs might look like:

enter image description here

and we can write a simple expression such as:

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

We can also add more boundaries to it, if it was necessary.

RegEx

If this expression wasn't desired, you can modify/change your expressions in regex101.com.

RegEx Circuit

You can also visualize your expressions in jex.im:

enter image description here

PHP Test

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

$result = preg_replace($re, $subst, $str);

echo $result;

JavaScript Demo

This snippet shows that we likely have a valid expression:

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);
Community
  • 1
  • 1
Emma
  • 27,428
  • 11
  • 44
  • 69