Let\'s take these URLs as an example:
Here is my function for retrieving Youtube ID !
function getYouTubeId($url) {
if (!(strpos($url, 'v=') !== false)) return false;
$parse = explode('v=', $url);
$code = $parse[1];
if (strlen($code) < 11) return false;
$code = substr($code, 0, 11);
return $code;
}
Here is one solution
/**
* credits goes to: http://stackoverflow.com/questions/11438544/php-regex-for-youtube-video-id
* update: mobile link detection
*/
public function parseYouTubeUrl($url)
{
$pattern = '#^(?:https?://)?(?:www\.)?(?:m\.)?(?: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;
}
It can deal with mobile links too.
Instead of regex. I hightly recommend parse_url() and parse_str():
$url = "http://www.youtube.com/watch?v=8GqqjVXhfMU&feature=youtube_gdata_player";
parse_str(parse_url( $url, PHP_URL_QUERY ), $vars );
echo $vars['v'];
Done