Skip to content

Instantly share code, notes, and snippets.

@onetarek
Forked from simplethemes/youtube-url.php
Created September 22, 2017 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onetarek/3df4a01e3c7f4121301efe3bedef0797 to your computer and use it in GitHub Desktop.
Save onetarek/3df4a01e3c7f4121301efe3bedef0797 to your computer and use it in GitHub Desktop.
Extracts YouTube video ID from various URL structures
<?php
$url = array (
'http://youtu.be/dQw4w9WgXcA',
'http://www.youtube.com/embed/dQw4w9WgXcB',
'http://www.youtube.com/watch?v=dQw4w9WgXcC',
'http://www.youtube.com/?v=dQw4w9WgXcD',
'http://www.youtube.com/v/dQw4w9WgXcE',
'http://www.youtube.com/e/dQw4w9WgXcF',
'http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcG',
'http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcH',
'http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcI',
'http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcJ'
);
// Extracts the YouTube ID from various URL structures
foreach ($url as $value) {
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $value, $match)) {
$id = $match[1];
var_dump($id);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment