Skip to content

Instantly share code, notes, and snippets.

@mcbrwr
Last active March 4, 2016 08:12
Show Gist options
  • Save mcbrwr/e45049073a2d3c81def2 to your computer and use it in GitHub Desktop.
Save mcbrwr/e45049073a2d3c81def2 to your computer and use it in GitHub Desktop.
throw in a string, returns embed code. Some use vimeo, others youtube, some insert the full URL, others just the key.. This returns the right embed code. If all fails it just returns the string (let's hope it's an embed code then ;-)
/**
* parse a string and return the appropriate embed code
* @return string
*/
public function parseMedia($string)
{
if (empty($string)) return false;
$rgx = '/^https*:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+))/';
preg_match($rgx, $string, $matches);
if (!empty($matches[1])) {
$type = $matches[1];
if ($type == 'youtube' && !empty($matches[3])) {
return $this->youtubeEmbed($matches[3]);
}
else if ($type == 'vimeo' && !empty($matches[2])) {
return $this->vimeoEmbed($matches[2]);
}
}
// 8-10 digits.. probably vimeo..
if (preg_match('/^\d{8,11}$/', $string)) {
return $this->vimeoEmbed($string);
}
// 11 word characters.. probably youtube
elseif(preg_match('/^[\w-]{11}$/',$string)) {
return $this->youtubeEmbed($string);
}
// unsure.. just swing back the thing..
return $string;
}
/**
* youtube embed code based on key
* @return string
*/
public function youtubeEmbed($key)
{
$html = '<div class="video youtube">';
$html .= '<iframe width="560" height="315" src="https://www.youtube.com/embed/'.$key;
$html .= '" frameborder="0" allowfullscreen></iframe>';
$html .= '" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
$html .= '</div>';
return $html;
}
/**
* vimeo embed code based on key
* @return string
*/
public function vimeoEmbed($key)
{
$html = '<div class="video vimeo">';
$html .= '<iframe src="https://player.vimeo.com/video/' . $key;
$html .= '" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
$html .= '</div>';
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment