Skip to content

Instantly share code, notes, and snippets.

@sixlive
Last active March 7, 2016 16:10
Show Gist options
  • Save sixlive/be6ca16e4a37e3631902 to your computer and use it in GitHub Desktop.
Save sixlive/be6ca16e4a37e3631902 to your computer and use it in GitHub Desktop.
PHP: Gets the video code from a YouTube video URL.
<?php
/**
* Returns the ID of a YouTube Video URL
*
* This works with both the short and full URL.
*
* @param string $url The video URL
* @return string The video ID
* @author TJ Miller http://tjay.co
*/
function getYoutubeCode($url)
{
$parts = [];
$video_code = false;
if (preg_match('/youtu.be/', $url)) {
$video_code = preg_match_all('/youtu\.be\/(.*)\??/', $url, $matches);
$video_code = $matches[1][0];
} else {
preg_match('/(\?v\=)+(.{11})/', $url, $parts);
$video_code = substr($parts[0], -11);
}
return $video_code;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment