Posted By

Moridin on 09/03/09


Tagged

video id YouTube


Versions (?)

Who likes this?

13 people have marked this snippet as a favorite

aelien
umang_nine
sveggiani
mihael
Onfire60
ofadlaoui
motionmediasolutions
dimispaceman
damarev
mdsol
silky
clacwebstudio
rentnil


Retrieve YouTube video ID from a YT URL


 / Published in: PHP
 

This code allows you to retrieve the 11-character ID string from a YouTube video URL.

  1. /*
  2. * Retrieve the video ID from a YouTube video URL
  3. * @param $ytURL The full YouTube URL from which the ID will be extracted
  4. * @return $ytvID The YouTube video ID string
  5. */
  6. function getYTid($ytURL) {
  7.  
  8. $ytvIDlen = 11; // This is the length of YouTube's video IDs
  9.  
  10. // The ID string starts after "v=", which is usually right after
  11. // "youtube.com/watch?" in the URL
  12. $idStarts = strpos($ytURL, "?v=");
  13.  
  14. // In case the "v=" is NOT right after the "?" (not likely, but I like to keep my
  15. // bases covered), it will be after an "&":
  16. if($idStarts === FALSE)
  17. $idStarts = strpos($ytURL, "&v=");
  18. // If still FALSE, URL doesn't have a vid ID
  19. if($idStarts === FALSE)
  20. die("YouTube video ID not found. Please double-check your URL.");
  21.  
  22. // Offset the start location to match the beginning of the ID string
  23. $idStarts +=3;
  24.  
  25. // Get the ID string and return it
  26. $ytvID = substr($ytURL, $idStarts, $ytvIDlen);
  27.  
  28. return $ytvID;
  29.  
  30. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: n0ta on March 15, 2011

Works great. Thank you!

You need to login to post a comment.