Skip to content

Instantly share code, notes, and snippets.

@banksy89
Created July 3, 2012 16:44
Show Gist options
  • Save banksy89/3040922 to your computer and use it in GitHub Desktop.
Save banksy89/3040922 to your computer and use it in GitHub Desktop.
Gets the main image for a YouTube image, to be used for a placeholder.
function getYouTubeKey ( $video )
{
preg_match ( '#\\?v=([^&]+)\\&#s', $video, $vid );
if ( count ( $vid ) > 0 )
{
// The correct match is the second item in array
return $vid[ 1 ];
}
else
return $video;
}
$video = 'http://www.youtube.com/watch?v=XlpC8-9iI0A&feature=g-vrec';
<img src="http://img.youtube.com/vi/<?php echo getYouTubeKey ( $video ); ?>/2.jpg" width="663" height="365">
@Integralist
Copy link

For the regex, instead of (.+) you would be better doing something like ([^&]+) which basically means match anything BUT NOT the ampersand. This should be better performing than the . Character as it'll mean less backtracking by the regex engine

@banksy89
Copy link
Author

banksy89 commented Jul 4, 2012

Cool! Changed and works nicely

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment