Parse YouTube URLs With PHP

youtube logo 05 Parse YouTube URLs With PHPHere’s a nice PHP snippet that some of you might find useful with regards to information on YouTube videos. It’s a code that I came across over at PHPZAG that will parse the various types of YouTube URLs and then returning their embed iframe.

<?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;
}
}
 ?>

The above code comes with optional width and height.

Incoming search terms for the article:

Related Posts

Turn A Photo Into A Vector Portrait With Photoshop

Correctly Embed Watermarks In Portrait And Landscape Photos Using Conditional Actions In Photoshop CS6.1

Oregon-Inspired Photoshop Tutorial

Create Google Play’s Tab Navigation Using jQuery And CSS

1 Comment

  1. Moko

    07.21.2012

    Have you ever thought about including a little bit more than just your articles?

    I mean, what you say is valuable and all. Nevertheless just imagine if
    you added some great graphics or video clips to give your posts more, “pop”! Your content is excellent but with images and videos, this blog could certainly be one of the very best in its field. Amazing blog!