Recent Posts

Showing posts with label video. Show all posts
Showing posts with label video. Show all posts

How to parse YouTube video URL using preg_match in PHP

This 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)