Different YouTube video thumbnail URLs

To get the different thumbnails of embedded video from YouTube, use these image URLs for different dimensions,

1) For medium sized thumbnail image
http://i.ytimg.com/vi/<YouTube Video ID>/0.jpg

2)  For small sized thumbnail image

http://i.ytimg.com/vi/<YouTube Video ID>/1.jpg
http://i.ytimg.com/vi/<YouTube Video ID>/2.jpg
http://i.ytimg.com/vi/<YouTube Video ID>/3.jpg

3) For large or maximum sized thumbnail image

http://i.ytimg.com/vi/<YouTube Video ID>/maxresdefault.jpg

4) For High Definition Image

http://img.youtube.com/vi/<YouTube Video ID>/hqdefault.jpg

In above URLs, provide <YouTube Video ID>. To get Video ID from YouTube URL,

  • Go to http://www.youtube.com
  • Play any video
  • Copy an alphanumeric string followed by v= from URL

This is a Video ID of currently playing video.

For example:

Video ID of YouTube Video https://www.youtube.com/watch?v=ny8ngucMd_U is ny8ngucMd_U

Use this video ID in above thumbnail URLs to get different thumbnail image of this video.

Find YouTube Video ID from YouTube URL

YouTube has so many types of URLs to embed the video on your site. Sometimes it’s difficult to find a single regular expression to parse all type of YouTube URL and retrieve the video ID from it.

YouTube has so many types of URLs to embed the video on your site. Sometimes it’s difficult to find a single regular expression to parse all type of YouTube URL and retrieve the video ID from it.

To retrieve the video ID from the YouTube URL, use this function,

function getVideoID($url) {
    $pattern = '#^(?:https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=|/watch\?.+&v=))([\w-]{11})(?:.+)?$#x';
    preg_match($pattern, $url, $matches);
    return (isset($matches[1])) ? $matches[1] : false;
}

Regular Expression explanation is as follows,

$pattern = '#^(?:https?://)?';    # Either http or https.
$pattern .= '(?:www\.)?';         #  Optional, www subdomain.
$pattern .= '(?:';                #  Group host alternatives:
$pattern .=   'youtu\.be/';       #    Either youtu.be,
$pattern .=   '|youtube\.com';    #    or youtube.com
$pattern .=   '(?:';              #    Group path alternatives:
$pattern .=     '/embed/';        #      Either /embed/,
$pattern .=     '|/v/';           #      or /v/,
$pattern .=     '|/watch\?v=';    #      or /watch?v=,    
$pattern .=     '|/watch\?.+&v='; #      or /watch?other_param&v=
$pattern .=   ')';                #    End path alternatives.
$pattern .= ')';                  #  End host alternatives.
$pattern .= '([\w-]{11})';        # Youtube video ids with standard length of 11 chars.
$pattern .= '(?:.+)?$#x';         # Optional other ending URL parameters.