Snippet to get the youtube id from an url in PHP

Snippet to get the youtube id from an url in PHP


public static function parseYouTube($str) {
                $youtube_id_length = 11;
               
                if (preg_match(‘#((\?|\&)v\=|/embed/|/v/|/youtu.be/|\#././.+?/)(.{’.$youtube_id_length.‘})#i’, $str, $matches))
                        return $matches[3];
                else {
                        if (mb_strpos($str,‘/user/’) !== false) {
                                return mb_substr($str,strlen($str)-11,11);
                        } else {
                                return $str;
                        }
                };
               
                /*
                Currently works for the following url formats.
                http://youtu.be/7-luJRn6u9c
                http://youtube.com/embed/7-luJRn6u9c
                http://youtube.com/v/7-luJRn6u9c
                http://youtube.com?v=7-luJRn6u9c
                http://youtube.com/watch?v=7-luJRn6u9c
                http://www.youtube.com/HuskyStarcraft#p/u/5/7-luJRn6u9c
                http://www.youtube.com/user/HuskyStarcraft#p/u/1/7-luJRn6u9c
                */
             
        }
 

Credits for Ramsez Stamper