Get YouTube ID from emebed url : MODx Output Filter

Update 4/24/2013 - 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.

 * 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,
       | youtube\.com  # or
         (?:           # 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.
    $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


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

<img class="thumbnail" src="[[]]/hqdefault.jpg" /></a>

Please post other ideas and suggestions below.

Comments (0)

Add a Comment

Allowed tags: <b><i><br>Add a new comment: