Get YouTube Video ID [Very robust]


/ Published in: PHP

This will get the 11-character YouTube video ID from any valid YouTube URL.

Based on http://snipplr.com/view/57065/get-youtube-video-id/ but made more robust to handle additional URL inputs


Copy this code and paste it in your HTML
  1. /**
  2.  * Get 11-character YouTube video ID from a URL
  3.  *
  4.  * @param string $url URL to video
  5.  * @return string|false False on invalid URL, 11 character string on success
  6.  */
  7. function getYouTubeId($url) {
  8. // Format all domains to http://domain for easier URL parsing
  9. str_replace('https://', 'http://', $url);
  10. if (!stristr($url, 'http://') && (strlen($url) != 11)) {
  11. $url = 'http://' . $url;
  12. }
  13. $url = str_replace('http://www.', 'http://', $url);
  14.  
  15. if (strlen($url) == 11) {
  16. $code = $url;
  17. } else if (preg_match('/http:\/\/youtu.be/', $url)) {
  18. $url = parse_url($url, PHP_URL_PATH);
  19. $code = substr($url, 1, 11);
  20. } else if (preg_match('/watch/', $url)) {
  21. $arr = parse_url($url);
  22. parse_str($url);
  23. $code = isset($v) ? substr($v, 0, 11) : false;
  24. } else if (preg_match('/http:\/\/youtube.com\/v/', $url)) {
  25. $url = parse_url($url, PHP_URL_PATH);
  26. $code = substr($url, 3, 11);
  27. } else if (preg_match('/http:\/\/youtube.com\/embed/', $url, $matches)) {
  28. $url = parse_url($url, PHP_URL_PATH);
  29. $code = substr($url, 7, 11);
  30. } else if (preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+#", $url, $matches) ) {
  31. $code = substr($matches[0], 0, 11);
  32. } else {
  33. $code = false;
  34. }
  35.  
  36. if ($code && (strlen($code) < 11)) {
  37. $code = false;
  38. }
  39.  
  40. return $code;
  41. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.