Skip to content

Instantly share code, notes, and snippets.

@dieppon
Last active September 13, 2022 11:45
Show Gist options
  • Save dieppon/b14bb542ebc96ce0cb66946a6efc4cda to your computer and use it in GitHub Desktop.
Save dieppon/b14bb542ebc96ce0cb66946a6efc4cda to your computer and use it in GitHub Desktop.
Parse url from YouTube and Vimeo and return an array with: type, ID, thumbnail, url, embed url and embed iframe.
<?php
/**
* Parse url from YouTube and Vimeo and return an array with: type, ID, thumbnail, url, embed url and embed iframe.
*
* @param string $url
* @return array
*/
function parse_video_url($url) {
$output = array();
if (preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=embed/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $url, $matches)) {
$output['type'] = 'youtube';
$output['id'] = $matches[0];
$output['url'] = 'https://www.youtube.com/watch?v=' . $matches[0];
$output['thumb'] = 'http://img.youtube.com/vi/' . $matches[0] . '/maxresdefault.jpg';
$output['embed_url'] = 'https://www.youtube.com/embed/' . $matches[0];
$output['embed'] = '<iframe src="https://www.youtube.com/embed/' . $matches[0] . '?controls=0&autoplay=1&mute=1&playsinline=1&loop=1&playlist=' . $matches[0] . '"></iframe>';
}
if (preg_match("/(https?:\/\/)?(www\.)?(player\.)?vimeo\.com\/?(showcase\/)*([0-9))([a-z]*\/)*([0-9]{6,11})[?]?.*/", $url, $matches)) {
$object = json_decode(file_get_contents('https://vimeo.com/api/oembed.json?url=https://vimeo.com/' . $matches[6]), true);
$output['type'] = 'vimeo';
$output['id'] = $matches[6];
$output['url'] = 'https://vimeo.com/' . $matches[6];
if ($object) {
$output['thumb'] = $object['thumbnail_url'];
} else {
$output['thumb'] = null;
}
$output['embed_url'] = 'https://player.vimeo.com/video/' . $matches[6];
$output['embed'] = '<iframe src="https://player.vimeo.com/video/' . $matches[6] . '?background=1&autoplay=1&loop=1&byline=0&title=0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
}
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment