The Solution
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) { $video_id = $match[1]; }
The Explanation
The piece PHP code above will allow you to extract the ID number inside of various youtube URLs. This helps you so that your client isn’t required to remember which URL will work when the post a custom field. Here is how we utilized it recently inside the WordPress Loop:
<?php $pattern = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i'; ?> <?php preg_match($pattern, $video, $videoid); ?> <a href="http://www.youtube.com/watch?v=<?php echo $videoid[1]; ?>" title="<?php the_title(); ?>" rel="prettyPhoto" class="vidthumb vidlist"><img src="http://i1.ytimg.com/vi/<?php echo $videoid[1]; ?>/0.jpg" width="220" style="margin-bottom:10px;" alt="<?php the_title(); ?>" /></a>
NOTE: The IMG is being pulled from YouTube as well. It is automatically getting the thumbnail that youtube provides.
URLs this works for:
http://youtu.be/AoKIM1iCqG0 http://www.youtube.com/?v=AoKIM1iCqG0 http://www.youtube.com/e/AoKIM1iCqG0 http://www.youtube.com/user/username#p/u/11/AoKIM1iCqG0 http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/AoKIM1iCqG0 http://www.youtube.com/?feature=player_embedded&v=AoKIM1iCqG0