How to get video id from YouTube video URL in PHP || Used to Create Youtube Gallery



Here is how you can get the YouTube Video ID from a URL no matter how many extra parameters get passed along with it.Method-1 used for it.In method-2 REGULAR EXPRESSION used to get video id from YouTube video URL.

Source Code:
Method-1:

function getYouTubeIdFromURL($url)
{
$url_string = parse_url($url, PHP_URL_QUERY);
parse_str($url_string, $args);
return isset($args[‘v’]) ? $args[‘v’] : false;
}

//copy a video link from youtube

$videoURL=”

$videoID=getYouTubeIdFromURL($videoURL);

Method-2:

function youtube_parse_youtube_id( $data )
{
// IF 11 CHARS, it means that data is video id
if( strlen($data) == 11 )
{
return $data;
}

preg_match( “/^.*(youtu.be/|v/|u/w/|embed/|watch?v=|&v=)([^#&?]*).*/”, $data, $matches);
return isset($matches[2]) ? $matches[2] : false;
}

$videoURL=”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.