Skip to content

Instantly share code, notes, and snippets.

@dimmduh
Created October 17, 2012 12:00
Show Gist options
  • Select an option

  • Save dimmduh/3905174 to your computer and use it in GitHub Desktop.

Select an option

Save dimmduh/3905174 to your computer and use it in GitHub Desktop.
youtube-replace-url
function replaceLinkToIframe($text, $width = 480, $height = 390)
{
$text = preg_replace('~
# Match non-linked youtube URL in the wild. (Rev:20111012)
https?:// # Required scheme. Either http or https.
(?:[0-9A-Z-]+\.)? # Optional subdomain.
(?: # Group host alternatives.
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com followed by
\S* # Allow anything up to VIDEO_ID,
[^\w\-\s] # but char before ID is non-ID char.
) # End host alternatives.
([\w\-]{11}) # $1: VIDEO_ID is exactly 11 chars.
(?=[^\w\-]|$) # Assert next char is non-ID or EOS.
(?! # Assert URL is not pre-linked.
[?=&+%\w]* # Allow URL (query) remainder.
(?: # Group pre-linked alternatives.
[\'"][^<>]*> # Either inside a start tag,
| </a> # or inside <a> element text contents.
) # End recognized pre-linked alts.
) # End negative lookahead assertion.
[?=&+%\w-]* # Consume any URL (query) remainder.
~ix',
'<a href="$0">watch video</a><div class="video-youtube" style="display:none"><iframe width="' . $width .'" height="' . $height .'" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe></div>',
$text);
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment