Quantcast
Channel: Developer Feed - Snippet
Viewing all articles
Browse latest Browse all 178

How to get Youtube Video Id from the URL using PHP?

$
0
0

Random Quotes in PHPGiven a YouTube Video URL can you find the VID from the URL?.The following Phip snippet helps you to do the same. The key things to keep in mind that VID which is a unique string for any video is 11 characters in length. Also the VID is represented by a v parameter in the URL.

An example of YouTube view URL can be

http://www.youtube.com/watch?v=Ig6c3P4ODC4

or

http://www.youtube.com/watch?feature=player_embedded&v=Ig6c3P4ODC4

In other words the v parameter can be any where in the URL.

<!--break-->

  1. function getYoutubeVideoId($url){
  2.  
  3. // len of video id
  4. $vidlen=11;
  5.  
  6. // Search for the v paramter in the url "youtube.com/watch?v=" in the URL
  7. $index=strpos($url,"?v=");
  8.  
  9. // if not found, search with an &v
  10. if($index===FALSE){
  11.    $index=strpos($url,"&v=");
  12. }
  13.  
  14. // not found
  15. if($index===FALSE){
  16.         // cannot find it
  17.         return"";
  18. }
  19.  
  20. # offset 3 chars to position to the begin
  21. $index=$index+3;
  22.  
  23. // Substring and find the vid
  24. $vid=substr($url,$index,$vidlen);
  25.  
  26. return$vid;
  27.  
  28. }

Viewing all articles
Browse latest Browse all 178

Trending Articles