RegEx pattern to get the YouTube video ID from any YouTube URL

后端 未结 9 1973
南方客
南方客 2020-11-27 17:48

Let\'s take these URLs as an example:

  1. http://www.youtube.com/watch?v=8GqqjVXhfMU&feature=youtube_gdata_player
  2. http://www.youtube.com/watch?v=8Gqqj
9条回答
  •  抹茶落季
    2020-11-27 18:23

    I have used the following patterns because YouTube has a youtube-nocookie.com domain too:

    '@youtube(?:-nocookie)?\.com/watch[#\?].*?v=([^"\& ]+)@i',
    '@youtube(?:-nocookie)?\.com/embed/([^"\&\? ]+)@i',
    '@youtube(?:-nocookie)?\.com/v/([^"\&\? ]+)@i',
    '@youtube(?:-nocookie)?\.com/\?v=([^"\& ]+)@i',
    '@youtu\.be/([^"\&\? ]+)@i',
    '@gdata\.youtube\.com/feeds/api/videos/([^"\&\? ]+)@i',
    

    In your case it would only mean to extend the existing expressions with an optional (-nocookie) for the regular YouTube.com URL like so:

    if (preg_match('/youtube(?:-nocookie)\.com\/watch\?v=([^\&\?\/]+)/', $url, $id)) {
    

    If you change your proposed expression to NOT contain the final $, it should work like you intended. I added the -nocookie as well.

    /**
     * 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(?:-nocookie)?\.com  # or youtube.com and youtube-nocookie
              (?:           # 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 !== $result) {
            return $matches[1];
        }
        return false;
    }
    

提交回复
热议问题