Get YouTube Video ID with PHP

If you need to extract a youtube video id from a URL, it's actually very simple.

There are many ways to skin a cat and the YouTube Video ID "cat" is no exception.

YouTube video ids are passed as a GET variable, using a key of "v", so the most obvious way to get the value would be to use a RegExp.

That said, RegExps can often be confusing so while they will work, there is another way - the native way...

PHP has built in functions as I'm sure you know, and there are 2 that will do the job perfectly for us: parse_str and parse_url.

PARSE_URL takes a url as a string, and cuts it up into sections for you, returning the results in an array. You can work with the whole array, or simply tell the function which part you want. In our case, we are interested in the query, so we'll tell it to only return the PHP_URL_QUERY.

The query though, could have a number of items in it such as v, related, featured, etc. We only need the value of v, as this is the Video ID. PARSE_STR works on a string in the same way that $_GET works on a URL, so by running parse_str on our query, it will put everything into their key => value pairs, and store the results in an array.

Sound simple?

Here is an example:

= "";
( parse_url( $url, PHP_URL_QUERY ), $url_vars );
echo $url_vars
// Output: 7zWKm-LZWm4

You now have a YouTube Video ID without using a RegExp ;)