Extracting YouTube video ID

Hello,

What I tried to do is get video ID out of youtube url:

http://www.youtube.com/watch?v=loTSjUF-cMM&playnext_from=TL&videos=kBQ8m1HsvIw&feature=sub

So here is what I did put together:

function getID($url)
{
	$id = "";
	if(strstr($url, 'youtube.com/watch?v='))
	{
		$token = explode('=', $url);
		if(strstr($token[1], '&'))
		{
			$token2 = explode('&', $token[1]);
			$id =  $token2[0];
		}
		else{
			$id = $token[1];
		}
	}
	
	return $id;
}

Although I am wondering if I could make this thing a bit more failproof and less complicated by regex match (preg_match()), although I don’t know how to write the pattern. Help.


$videoId = false;
$queryString = parse_url('http://www.youtube.com/watch?v=ESka_Ao9Fmo&feature=fvw', PHP_URL_QUERY);
parse_str($queryString, $qsVariables);
if (isset($qsVariables['v'])
{
    $videoId = $qsVariables['v'];
}