PHP – Parse YouTube URLS
Here is a simple php code that will parses the various types of YouTube URLs and returning the embed iframe
with optional width and height.
Example Code:
- <?php
- function parseYoutubeURL($link, $width=430, $height=230){
- $final = ‘<iframe width=”‘.$width.‘” height=”‘.$height.‘” src=”http://www.youtube.com/embed/{code}” frameborder=”0″></iframe>’;
- //se o link for o embed (altera o width e height)
- if(stristr($link, “iframe”)){
- $link = preg_replace(“/width=(\”)[0-9]+(\”)/”, ‘width=”‘.$width.‘”‘, $link);
- $link = preg_replace(“/height=(\”)[0-9]+(\”)/”, ‘height=”‘.$height.‘”‘, $link);
- return $link;
- }
- $parsed = parse_url($link);
- //link URL
- if(stristr($parsed['path'], ‘watch’) !== false){
- parse_str($parsed['query'], $args);
- $code = $args['v'];
- }//link do embbed
- elseif(stristr($parsed['path'], ‘embed’) !== false){
- $code = str_replace(“/embed/”, “”, $parsed['path']);
- }//short link
- elseif($parsed['host'] == ‘youtu.be’){
- $code = str_replace(“/”, “”, $parsed['path']);
- }
- if($code){
- $final = str_replace(“{code}”, $code, $final);
- return $final;
- }else{
- return null;
- }
- }
- ?>
Follow @phpzag

I was very happy to find this site. I wanted to thank you for ones time due to this wonderful read!! I definitely liked every part of it and i also have you bookmarked to see new information on your website.
Howdy! Would you mind if I share your blog with my twitter group? There’s plenty of folks that I think would truly enjoy your content. Please let me know. Thanks