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

后端 未结 9 1862
南方客
南方客 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:27

    Here is my function for retrieving Youtube ID !

    function getYouTubeId($url) {
        if (!(strpos($url, 'v=') !== false)) return false;
        $parse = explode('v=', $url);
        $code = $parse[1];
        if (strlen($code) < 11) return false;
        $code = substr($code, 0, 11);
        return $code;
    }
    
    0 讨论(0)
  • 2020-11-27 18:29

    Here is one solution

    /**
     * credits goes to: http://stackoverflow.com/questions/11438544/php-regex-for-youtube-video-id
     * update: mobile link detection
     */
    public function parseYouTubeUrl($url)
    {
         $pattern = '#^(?:https?://)?(?:www\.)?(?:m\.)?(?: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;
    }
    

    It can deal with mobile links too.

    0 讨论(0)
  • 2020-11-27 18:32

    Instead of regex. I hightly recommend parse_url() and parse_str():

    $url = "http://www.youtube.com/watch?v=8GqqjVXhfMU&feature=youtube_gdata_player";
    parse_str(parse_url( $url, PHP_URL_QUERY ), $vars );
    echo $vars['v'];    
    

    Done

    0 讨论(0)
提交回复
热议问题