Wednesday, October 10, 2012

9:07 AM
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.


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

0 comments: