Get YouTube Video ID with PHP
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:
<?php
$url = "https://www.youtube.com/watch?v=7zWKm-LZWm4&feature=relate";
parse_str( parse_url( $url, PHP_URL_QUERY ), $url_vars );
echo $url_vars['v'];
// Output: 7zWKm-LZWm4
?>
You now have a YouTube Video ID without using a RegExp ;)