Skip to content

Instantly share code, notes, and snippets.

@morningtoast
Created March 6, 2014 21:55
Show Gist options
  • Save morningtoast/9400516 to your computer and use it in GitHub Desktop.
Save morningtoast/9400516 to your computer and use it in GitHub Desktop.
YouTube URL replacer
function ytEmbed($str) {
$pattern = '/https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{11})[?=&+%\w-]*/i';
$found = preg_match_all($pattern, $str, $matches);
if ($found > 0) {
foreach ($matches[0] as $k => $replaceThis) {
$ytid = $matches[1][$k];
$replaceWith = '<div class="media"><div class="video-container"><iframe title="YouTube video" class="youtube-player" height="315" width="560" type="text/html" src="http://www.youtube.com/embed/'.$ytid.'" frameborder="0"></iframe></div></div>';
$str = str_replace($replaceThis, $replaceWith, $str);
}
}
return($str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment