Skip to content

Instantly share code, notes, and snippets.

@lutzissler
Created July 16, 2020 12:13
Show Gist options
  • Save lutzissler/b30f35470a4064c86ab37c9fa5ee34cc to your computer and use it in GitHub Desktop.
Save lutzissler/b30f35470a4064c86ab37c9fa5ee34cc to your computer and use it in GitHub Desktop.
Return the proper iframe URL for any YouTube, Vimeo, or SoundCloud URL. $cache is a PhpFastCache instance (but not required).
function get_embed_url($url) {
global $cache;
// Check for YouTube
$matchFound = preg_match('/^(https?:\/\/(www\.)?youtube\.com\/watch\?(t=(.+)&)?v=|https?:\/\/youtu\.be\/)([^?]+)(\?(t=(.+))?.*)?$/', $url, $matches);
if ($matchFound) {
// Video is a Youtube video
$url = '//www.youtube.com/embed/' . $matches[5];
if ($matches[4]) {
$url = $url . '?start=' . $matches[4];
} else if ($matches[8]) {
$url = $url . '?start=' . $matches[8];
}
} else {
// Check for Vimeo
$matchFound = preg_match('#^https?://vimeo\.com/([a-zA-Z0-9]+)/?$#', $url, $matches);
if ($matchFound) {
// Video is a Vimeo video
$url = '//player.vimeo.com/video/' . $matches[1] . '?byline=0&portrait=0';
} else if (substr($url, 0, 23) == 'https://soundcloud.com/') {
// Soundcloud
$cacheKey = 'oembed-' . md5($url);
if ($cache) {
$oembedData = $cache->get($cacheKey);
} else {
$oembedData = null;
}
if (!$oembedData) {
$oembedData = file_get_contents('https://soundcloud.com/oembed?format=json&url=' . urlencode($url));
if ($oembedData) {
$oembedData = json_decode($oembedData);
if (is_object($oembedData) && $cache) {
$cache->set($cacheKey, $oembedData);
}
}
}
if (is_object($oembedData) && $oembedData->html) {
$matchFound = preg_match('/src="(.+?)"/', $oembedData->html, $matches);
if ($matchFound) {
return $matches[1];
}
}
}
}
return $url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment