Breaking News
Home / Web / PHP / PHP Snippets / How to get Youtube Video Id from the URL using PHP?

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

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.

<!>

  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. }
[pb_builder]

Check Also

How to list files in a directory in PHP?

<?php if ($handle = opendir(‘/path/to/directory’)) {     echo "Directory handle: $handlen";     echo …

Advertisment ad adsense adlogger