Viewed   93 times

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;

(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&n]+|(?<=v=)[^&n]+

As shown in this pic:

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

<?
 $subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1";

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

 print "<pre>";
 print_r($matches);
 print "</pre>";

?>

Cheers

 Answers

2

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)

  • http://youtu.be/dQw4w9WgXcQ ...
  • http://www.youtube.com/embed/dQw4w9WgXcQ ...
  • http://www.youtube.com/watch?v=dQw4w9WgXcQ ...
  • http://www.youtube.com/?v=dQw4w9WgXcQ ...
  • http://www.youtube.com/v/dQw4w9WgXcQ ...
  • http://www.youtube.com/e/dQw4w9WgXcQ ...
  • http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ ...
  • http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ ...
  • http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ ...
  • http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ ...

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)

Monday, December 26, 2022
2

Try this answer from a previous question asked:

function parse_yturl($url) 
    {
        $pattern = '#^(?:https?://)?(?:www.)?(?:youtu.be/|youtube.com(?:/embed/|/v/|/watch?v=|/watch?.+&v=))([w-]{11})(?:.+)?$#x';
        preg_match($pattern, $url, $matches);
        return (isset($matches[1])) ? $matches[1] : false;
    }
Sunday, November 20, 2022
 
2

Here's an example solution:

PHP:

preg_replace('/.+(?|&)v=([a-zA-Z0-9]+).*/', 'http://youtube.com/watch?v=$2', 'http://www.youtube.com/watch?v=136pEZcb1Y0&feature=fvhl');

Match:

^.+(?|&)v=([a-zA-Z0-9]+).*$

Replace with:

http://youtube.com/watch?v=$2

Here's how it works: regex analyzer.

Tuesday, September 27, 2022
5

Like this:

$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
$video_id = explode("?v=", $link);
$video_id = $video_id[1];

Here is universal solution:

$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0&lololo";
$video_id = explode("?v=", $link); // For videos like http://www.youtube.com/watch?v=...
if (empty($video_id[1]))
    $video_id = explode("/v/", $link); // For videos like http://www.youtube.com/watch/v/..

$video_id = explode("&", $video_id[1]); // Deleting any other params
$video_id = $video_id[0];

Or just use this regex:

(?v=|/v/)([-a-zA-Z0-9]+)
Thursday, December 8, 2022
 
3

Doing a search with the API works with different YouTube URL types. The URL is passed as the query term q.

https://www.googleapis.com/youtube/v3/search/?key=<YOUR_KEY>&part=snippet&q=youtu.be/M7lc1UVf-VE

Maybe some case could result in more than one item, but the normal search result is just one match:

{
    kind: "youtube#searchListResponse",
    etag: ""m2yskBQFythfE4irbTIeOgYYfBU/j2Px-5q--mgJEsrfjg4L0Mgn_L8"",
    regionCode: "ES",
    pageInfo: {
        totalResults: 1,
        resultsPerPage: 5
    },
    items: [
        {
            kind: "youtube#searchResult",
            etag: ""m2yskBQFythfE4irbTIeOgYYfBU/_1gFVi_i_djlS4OZWPGtcZ3iSLQ"",
            id: {
                kind: "youtube#video",
                videoId: "M7lc1UVf-VE"
            },
            snippet: {
                publishedAt: "2013-04-10T17:25:04.000Z",
                channelId: "UC_x5XG1OV2P6uZZ5FSM9Ttw",
                title: "YouTube Developers Live: Embedded Web Player Customization",
                description: "On this week's show, Jeff Posnick covers everything you need to know about using player parameters to customize the YouTube iframe-embedded player.",
                thumbnails: {
                    default: {
                        url: "https://i.ytimg.com/vi/M7lc1UVf-VE/default.jpg",
                        width: 120,
                        height: 90
                    },
                    medium: {
                        url: "https://i.ytimg.com/vi/M7lc1UVf-VE/mqdefault.jpg",
                        width: 320,
                        height: 180
                    },
                    high: {
                        url: "https://i.ytimg.com/vi/M7lc1UVf-VE/hqdefault.jpg",
                        width: 480,
                        height: 360
                    }
                },
                channelTitle: "Google Developers",
                liveBroadcastContent: "none"
            }
        }
    ]
}

I tested with some of the URL variations from this answer and most worked:

var urls = [
    '//www.youtube-nocookie.com/embed/M7lc1UVf-VE?rel=0',
    'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=channel',
    'https://www.youtube.com/watch?v=M7lc1UVf-VE&playnext_from=TL&videos=osPknwzXEas&feature=sub',
    'https://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I', // <---- invalid
    'https://youtu.be/M7lc1UVf-VE',
    'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=youtu.be',
    'https://youtu.be/M7lc1UVf-VE',
    'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=channel',
    'https://www.youtube.com/watch?v=M7lc1UVf-VE&playnext_from=TL&videos=osPknwzXEas&feature=sub',
    'https://www.youtube.com/ytscreeningroom?v=M7lc1UVf-VE', // <---- invalid
    'https://www.youtube.com/embed/M7lc1UVf-VE?rel=0',
    'https://www.youtube.com/watch?v=M7lc1UVf-VE',
    'https://youtube.com/v/M7lc1UVf-VE?feature=youtube_gdata_player',
    'https://youtube.com/vi/M7lc1UVf-VE?feature=youtube_gdata_player', // <---- invalid
    'https://youtube.com/?v=M7lc1UVf-VE&feature=youtube_gdata_player',
    'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=youtube_gdata_player',
    'https://youtube.com/?vi=M7lc1UVf-VE&feature=youtube_gdata_player', // <---- invalid
    'https://youtube.com/watch?v=M7lc1UVf-VE&feature=youtube_gdata_player',
    'https://youtube.com/watch?vi=M7lc1UVf-VE&feature=youtube_gdata_player',
    'https://youtu.be/M7lc1UVf-VE?feature=youtube_gdata_player'
];

var my_key = '<YOUR_KEY>';

function getUri(uri){
    $.get('https://www.googleapis.com/youtube/v3/search/?key='+my_key+'&part=snippet&q='+uri, function(data) {
        if(data.items.length !== 0)
            console.log(data.items[0].snippet.publishedAt);
        else
            console.warn('no items for',uri)
    });
}

for (i = 0; i < urls.length; ++i) {
    getUri(urls[i]);
}
Friday, September 2, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :