PHP Function: Get the YouTube Video Id from a YouTube URL


Here is how you can get the YouTube Video ID from a URL no matter how many extra parameters get passed along with it.

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

Call it:

$youtube_id = getYouTubeIdFromURL("http://www.youtube.com/watch?v=jhjhkum-kq8&feature=related");
echo $youtube_id;

// jhjhkum-kq8

 

Regular Expression YouTube ID Function

I found a Regular Expression on Stack Exchange that searches for a bunch of different YouTube URL. Here it is:

function youtube_parse_youtube_id( $data )
{
	// IF 11 CHARS
	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;
}