Skip to content

Instantly share code, notes, and snippets.

@aslamdoctor
Forked from ghalusa/youtube_id_regex.php
Created October 11, 2021 15:51
  • Select an option

Select an option

Revisions

  1. aslamdoctor renamed this gist Oct 11, 2021. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. Goran Halusa created this gist Jun 20, 2015.
    20 changes: 20 additions & 0 deletions youtube_id_regex.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    <?php
    // Here is a sample of the URLs this regex matches: (there can be more content after the given URL that will be ignored)

    // http://youtu.be/dQw4w9WgXcQ
    // http://www.youtube.com/embed/dQw4w9WgXcQ
    // http://www.youtube.com/watch?v=dQw4w9WgXcQ
    // http://www.youtube.com/?v=dQw4w9WgXcQ
    // http://www.youtube.com/v/dQw4w9WgXcQ
    // http://www.youtube.com/e/dQw4w9WgXcQ
    // http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ
    // http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ
    // http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
    // http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ

    // It also works on the youtube-nocookie.com URL with the same above options.
    // It will also pull the ID from the URL in an embed code (both iframe and object tags)

    preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
    $youtube_id = $match[1];
    ?>