Posted By

jmiller on 01/03/12


Tagged

regex url parse video code id YouTube token


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Net-Freak


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

  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
Posted By: aalaap on July 27, 2012

This didn't work for a simple, basic YouTube URL, so I just went ahead and wrote my own:

function quickYouTubeId($youtubeurl) {
    preg_match("#[a-zA-Z0-9-]{11}#", $youtubeurl, $id);
    return (strlen($id[0])==11) ? $id[0] : false;
}

You can find this on GitHub.

Posted By: astralis on May 27, 2014

Not as good as this one that uses regex:

http://snipplr.com/view/74677/grab-youtube-video-id-and-thumbnail/

You need to login to post a comment.