How to Grab YouTube Video ID from URL in PHP

As I stated earlier, I would be sharing a few code snippets that I have found quite useful in the recent past.

Find below a few lines of code that will help if you ever need to extract the video ID from a YouTube link that you may, for one reason or another ask a user of your system to input.

This PHP regex grabs the ID from all of the various URLs I could find. There may be more out there, but I couldn’t find reference of them anywhere.

if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]
+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', 
$url, $match)) {
    $video_id = $match[1];
}

Here is a sample of the URLs this regex matches: (there can be more content after the given URL that will be ignored)

It also works on the youtube-nocookie.com URL with the same above options.

It will also pull the ID from the URL in an embed code (both iframe and object tags)

So there you have it. Now, you need not worry too much what kind of URL the user inputs into the field, you can easily get the video ID, and embed it in whatever fashion you may deem fit. Enjoy!

EDIT

Just in case you may have to perform this extraction a couple of times and would rather have it in a function…here you go

/**
 * get youtube video ID from URL
 *
 * @param string $url
 * @return string Youtube video id or FALSE if none found. 
 */
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'
        ;
    $result = preg_match($pattern, $url, $matches);
    if (false !== (bool)$result) {
        return $matches[1];
    }
    return false;
}

echo youtube_id_from_url('http://youtu.be/NLqAF9hrVbY'); # NLqAF9hrVbY

Enjoy!

Share

5 comments

  1. The return values of preg_match are 1, 0 or FALSE. FALSE if an error occured and 0 if the regexp doesn’t match. With this is mind, it would be better In the function version if you change

    if (false !== $result) {
    return $matches[1];
    }

    to

    if (false !== (bool)$result) {
    return $matches[1];
    }

    otherwise your function will return null for an url which doesn’t match.

Leave a Reply