ControlledChaos
4/12/2019 - 5:59 PM

PHP function to get youtube ID from URL

PHP function to get youtube ID from URL

<?php
function get_youtube_video_ID($youtube_video_url) {
  /**
  * Pattern matches
  * http://youtu.be/ID
  * http://www.youtube.com/embed/ID
  * http://www.youtube.com/watch?v=ID
  * http://www.youtube.com/?v=ID
  * http://www.youtube.com/v/ID
  * http://www.youtube.com/e/ID
  * http://www.youtube.com/user/username#p/u/11/ID
  * http://www.youtube.com/leogopal#p/c/playlistID/0/ID
  * http://www.youtube.com/watch?feature=player_embedded&v=ID
  * http://www.youtube.com/?feature=player_embedded&v=ID
  */
  $pattern = 
    '%                 
    (?:youtube                    # Match any youtube url www or no www , https or no https
    (?:-nocookie)?\.com/          # allows for the nocookie version too.
    (?:[^/]+/.+/                  # Once we have that, find the slashes
    |(?:v|e(?:mbed)?)/|.*[?&]v=)  # Check if its a video or if embed 
    |youtu\.be/)                  # Allow short URLs
    ([^"&?/ ]{11})                # Once its found check that its 11 chars.
    %i';

  // Checks if it matches a pattern and returns the value
  if (preg_match($pattern, $youtube_video_url, $match)) {
    return $match[1];
  }
  
  // if no match return false.
  return false;
}
?>