parse youtube video id using preg_match

J.C picture J.C · May 29, 2010 · Viewed 68.6k times · Source

I am attempting to parse the video ID of a youtube URL using preg_match. I found a regular expression on this site that appears to work;


As shown in this pic:

alt text

My PHP is as follows, but it doesn't work (gives Unknown modifier '[' error)...

 $subject = "";

 preg_match("(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+", $subject, $matches);

 print "<pre>";
 print "</pre>";




Benjam picture Benjam · Jun 17, 2011

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 you come across one this doesn't match, please leave a comment with the URL, and I'll try and update the regex to match your URL.

if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/\s]{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 URL with the same above options.

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