Getting the YouTube tag with PHP

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="<?php echo $videoid[1]; ?>" title="<?php the_title(); ?>" rel="prettyPhoto" class="vidthumb vidlist"><img src="<?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: