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.

Comments

comments