phpparse-url

How to correct the code that gets the YouTube ID to work with the short URL


I have a script that allows to grab videos from YouTube. However, it doesn't work if I use short URLs.

I think the problem is caused by the code that gets YouTube Id from URLs. Here are the lines I think are responsible for that:

$youtube_url = $_POST['file'];
$ParseUrl = parse_url($youtube_url);
parse_str($ParseUrl['query'], $youtube_url_prop);
$YouTubeId = isset($youtube_url_prop['v']) ? $youtube_url_prop['v'] : '';

I'm a newbie so first I would like to make sure that this is the code I should focus on.

If it so I hope someone can advice me how to change that lines to get YouTube Id also from short URLs.

Cheers.


Solution

  • This a function that will give you the video id for the both url format :

    <?php
    
    function extractVideoId($url) {
        $re = '/(youtu\.be\/|youtube\.com\/(watch\?(.*&)?v=|(embed|v)\/))([^\?&"\'>]+)/';
        preg_match($re, $url, $matches, PREG_OFFSET_CAPTURE, 0);
    
        if(!isset($matches[5])) {
            return null;
        }
        return $matches[5][0];
    }
    
    
    $fullUrl ="https://www.youtube.com/watch?v=dQw4w9WgXcQ";
    $shortUrl ="https://youtu.be/dQw4w9WgXcQ";
    
    var_dump(extractVideoId($fullUrl));
    var_dump(extractVideoId($shortUrl));
    

    Output :

    string(11) "dQw4w9WgXcQ"
    string(11) "dQw4w9WgXcQ"