Get the video id from the new youtu.be URLs

I have the following code that grabs the youtube video id from old shared urls (youtube.com/watch?v=adasdalkjsd)

        $url = $_GET['url']; 
        parse_str(parse_url($url, PHP_URL_QUERY), $query); 
        $video_id = isset($query['v']) ? $query['v'] : NULL; 

which works for the old ones, but I need a system that can work for both URLs. any suggestions?

+3
source share
1 answer

URLs, for example: http://youtu.be/QzEcJecXJC4?hd=1

$url = $_GET['url'];
$video_id = substr( parse_url($url, PHP_URL_PATH), 1 );

See parse_url . PHP_URL_PATH will provide you /QzEcJecXJC4, so you need to use substrto cut a slash.

+3
source

All Articles