Recent Posts

Showing posts with label YouTube. Show all posts
Showing posts with label YouTube. Show all posts

How to parse YouTube video URL using preg_match in PHP

This regex grabs the ID from all of the various URLs I could find... There may be more out there, but I couldn't find reference of them anywhere.

if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
    $video_id = $match[1];
}
Here is a sample of the URLs this regex matches: (there can be more content after the given URL that will be ignored)


It also works on the youtube-nocookie.com URL with the same above options.

It will also pull the ID from the URL in an embed code (both iframe and object tags)

How to: Get thumbnail from YouTube video API from PHP and cURL

Each YouTube video has 4 generated images. They are predictably formatted as follows:

http://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
http://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
http://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
http://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg
The first one in the list is a full size image and others are thumbnail images. The default thumbnail image (ie. one of 1.jpg2.jpg3.jpg) is:

http://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg
For the high quality version of the thumbnail use a url similar to this:

http://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg
There is also a medium quality version of the thumbnail, using a url similar to the HQ:

http://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg
For the standard definition version of the thumbnail, use a url similar to this:

http://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg
For the maximum resolution version of the thumbnail use a url similar to this:

http://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
All of the above urls are available over https too. Just change http to https in any of the above urls. Additionally, the slightly shorter hostname i3.ytimg.com works in place of img.youtube.com in the example urls above.

Alternatively, you can use the YouTube Data API (v3) or the older YouTube API v2.0 to get thumbnail images.