Skip to content

Instantly share code, notes, and snippets.

@imcarlosdev
Forked from jonasmello/get_video_by_url.php
Created August 8, 2017 20:07
Show Gist options
  • Save imcarlosdev/f0ea4a90b9db7348e57d3c4dde41a0bf to your computer and use it in GitHub Desktop.
Save imcarlosdev/f0ea4a90b9db7348e57d3c4dde41a0bf to your computer and use it in GitHub Desktop.
Convert Youtube or Vimeo url to iframe
<?php
function get_video_by_url($url, $params = null)
{
if (!is_string($url)) return false;
$regexVM = '~
# Match Vimeo link and embed code
(?:<iframe [^>]*src=")? # If iframe match up to first quote of src
(?: # Group vimeo url
https?:\/\/ # Either http or https
(?:[\w]+\.)* # Optional subdomains
vimeo\.com # Match vimeo.com
(?:[\/\w]*\/videos?)? # Optional video sub directory this handles groups links also
\/ # Slash before Id
([0-9]+) # $1: VIDEO_ID is numeric
[^\s]* # Not a space
) # End group
"? # Match end quote if part of src
(?:[^>]*></iframe>)? # Match the end of the iframe
(?:<p>.*</p>)? # Match any title information stuff
~ix';
$regExpYt = '~
^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*
~ix';
preg_match($regexVM, $url, $matches);
if (isset($matches[1]) && is_array($params) && isset($params['img']) && $params['img']) {
return '<a href="' . $url . '"' . (isset($params['class']) ? ' class="popup-vimeo ' . $params['class'] . '"' : '') . '><img src="" data-vmid="' . $matches[1] . '" alt=""></a>';
} else if (isset($matches[1])) {
return '<iframe class="video" src="https://player.vimeo.com/video/' . $matches[1] . '" width="500" height="449" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
}
preg_match($regExpYt, $url, $matches);
if (isset($matches[7]) && is_array($params) && isset($params['img']) && $params['img']) {
return '<a href="' . $url . '"' . (isset($params['class']) ? ' class="popup-youtube ' . $params['class'] . '"' : '') . '><img src="http://img.youtube.com/vi/' . $matches[7] . '/hqdefault.jpg" alt=""></a>';
} else if (isset($matches[7])) {
return '<iframe class="video" width="500" height="449" src="https://www.youtube.com/embed/' . $matches[7] . '" allowfullscreen></iframe>';
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment