Get YouTube ID from embed url : MODx Output Filter

Update 4/24/2013 - https://github.com/DashMedia/modx-youTubeId/blob/master/getYouTubeId.php This is a better solution.


We've been working on a new responsive website for Dan Schleck, a long time client, who needed a new website. He's been doing more youtube videos and I wanted an easy way to get the youtube ID but still easy for a client to input. I figured the url for the video would be easy enough.

I found a good article here on stack overflow on getting the youtube id from url. With Isaac's and Ryan's help we adapted it for MODx's awesome output filters.

<?php
/**
 * get youtube video ID from URL
 *
 * @param string $url
 * @return string Youtube video id or FALSE if none found.
 */
$url = $input;
if (!function_exists('youtube_id_from_url')) {
function youtube_id_from_url($url) {
    $pattern =
        '%^             # Match any youtube URL
       (?:https?://)?  # Optional scheme. Either http or https
       (?:www\.)?      # Optional www subdomain
       (?:             # Group host alternatives
         youtu\.be/    # Either youtu.be,
       | youtube\.com  # or youtube.com
         (?:           # Group path alternatives
           /embed/     # Either /embed/
         | /v/         # or /v/
         | /watch\?v=  # or /watch\?v=
         )             # End path alternatives.
       )               # End host alternatives.
       ([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
       $%x'
        ;
    $matches = array ();
    if (preg_match($pattern, $url, $matches)) {
        return $matches[1];
    }
    return false;
}
}
echo youtube_id_from_url($url); # NLqAF9hrVbY

The Code / Snippet / Output Filter

An output filter is just a snippet that you run with the template variable, placeholder or other variable data as being the input, simple yet powerful. It reminds me of Unix scripting, little programs that do one job and pass it on.

I saved this as a snippet called youtubeId

Uses

I used it here to pull the HD Thumbnail into a grid listing with a getResources snippet call.

<img class="thumbnail" src="http://img.youtube.com/vi/[[+tv.youtube:youtubeId]]/hqdefault.jpg" /></a>

Please post other ideas and suggestions below.

Recent Posts

Improving MODX Page Speed for Google

Your website speed is impacting your bottom line , here are a few ways to improve it through browser caching, asynchronous loading of resources and other tips and tricks.

The Status of Liquid Web Cloud Sites Formerly of Rackspace in 2018

We've been a cloudsites customer since our inception, it's had ups and downs, here is what we think about it now.

OG Image Branding with phpThumb and MODX

Some of our clients have wanted to make sure their logo and branding appear in facebook, twitter, or messaging apps when shared. We came up with a clever solution.