Skip to content

Instantly share code, notes, and snippets.

@Ahrengot
Created March 5, 2012 09:50
Show Gist options
  • Save Ahrengot/1977674 to your computer and use it in GitHub Desktop.
Save Ahrengot/1977674 to your computer and use it in GitHub Desktop.
Parses a URL and returns the correct video ID based on service.
/**
* Parses a URL and returns the correct video ID based on service.
*
* @param string $url the URL to parse
* @param string $service 'youtube', 'vimeo' etc.
*
* @return string
*/
function get_video_id($url, $service = 'youtube') {
$match = '';
switch ($service) {
case 'youtube':
$regex = "#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#";
if (preg_match($regex, $url, $match)) {
$match = $match[0];
}
break;
case 'vimeo':
$regex = "/vimeo\.com\/([^&]*)/i";
if (preg_match($regex, $url, $match)) {
$match = $match[1];
}
break;
case 'facebook':
parse_str(parse_url($url , PHP_URL_QUERY), $v);
$match = @$v['v'];
break;
default:
$match = 'get_video_id() > SERVICE NOT SUPPORTED!';
break;
}
return $match;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment