Web Dev Tid Bit: Grabbing the ID of a YouTube URL in PHP
We make a lot of templates that work with YouTube videos. Most of these videos are added by the client via a text field asking for the “YouTube URL”. What they put in there is not always exactly what you need for your particular application. For instance, there is the standard watching url you would see if you go to YouTube.com “https://www.youtube.com/watch?v=1Mlhnt0jMlg” , the shortened URL “https://youtu.be/1Mlhnt0jMlg”, and the embed URL “https://www.youtube.com/embed/1Mlhnt0jMlg”.
It isn’t realistic to expect a client to always know to give a specific version of the URL, and making any fields asking for just the YouTube ID is also inviting issues for some non tech-savvy people.
So what can we do?
Luckily there is a nifty little PHP function I’ve been using that I’ve found and tweaked that should get the ID of your the video every time ( as of September 2017 at least ).
$params = array();
preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $video_parts);
$params['id'] = $video_parts;
$params['id'] = $url;
preg_match("/list=(.*)&?\/?/", $url, $video_parts);
$params['list'] = $video_parts;
This uses a regular expression to find any iteration of a YouTube URL and to grab the relevant part that is the ID and return it as an array. As an added bonus, it also returns the playlist list ID if there is one present as well. So running this code:
print_r( pk_get_youtube_params('https://youtu.be/1Mlhnt0jMlg') );
Will give you a return of:
[id] => 1Mlhnt0jMlg
From there you can use that ID to formulate a different/correct URL or use it in a completely different way!