Today I wanted to be able to extract the youtube unique id for the video so that I could automatically embed any youtube video in my webpage.
What I wanted to be able to do was let the user copy + paste in a youtube url such as http://www.youtube.com/watch?v=pJf6S8FYTUo&feature=related and extract the value of the key ‘v’ which is obviously the video id.
After a short while I ran into a stackoverflow question which had an awesomely simple answer;
<?php $url = "http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=relate"; parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars ); echo $my_array_of_vars['v']; // Output: C4kxS1ksqtw ?> |
So what this means is that I can now just do the following to embed any youtube video in to a page;
<?php $url = "http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=relate"; parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars ); ?> <i frame src="http://www.youtube.com/embed/<?php echo $my_array_of_vars['v']; ?>" frameborder="0" width="560" height="315"> </i frame> |
*remove space between i frame (was to stop it from showing in the post)