Call
608.845.2900
Visit
330 Locust Dr.
Verona, WI 53593
Message
info@powderkegwebdesign.com
NEED SOME GUIDANCE ON PLANNING A NEW WEBSITE?
Download our free guide!
Powderkeg Web Design
Menu
Message Us
Nick
Nick

Web Dev Tid Bit: Grabbing the ID of a YouTube URL in PHP

September 22, 2017

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 ).

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:

Will give you a return of:

From there you can use that ID to formulate a different/correct URL or use it in a completely different way!

Nick
Nick
Senior Developer

Nick is an ambitious and versatile developer with a wide range of talents. He is an efficient coder that utilizes his resources in order to achieve both his and the clients’ goals. His Alma Mater is the University of Wisconsin – Stevens Point where he graduated with honors in Web and Digital Media Development.