PHP – Parse YouTube URLS

May 13th, 2012 by laeeq | 2 comments

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:
  1. <?php
  2. function parseYoutubeURL($link, $width=430, $height=230){
  3. $final = ‘<iframe width=”‘.$width.‘” height=”‘.$height.‘” src=”http://www.youtube.com/embed/{code}” frameborder=”0″></iframe>’;
  4. //se o link for o embed (altera o width e height)
  5. if(stristr($link, “iframe”)){
  6. $link = preg_replace(“/width=(\”)[0-9]+(\”)/”, ‘width=”‘.$width.‘”‘, $link);
  7. $link = preg_replace(“/height=(\”)[0-9]+(\”)/”, ‘height=”‘.$height.‘”‘, $link);
  8. return $link;
  9. }
  10. $parsed = parse_url($link);
  11. //link URL
  12. if(stristr($parsed['path'], ‘watch’) !== false){
  13. parse_str($parsed['query'], $args);
  14. $code = $args['v'];
  15. }//link do embbed
  16. elseif(stristr($parsed['path'], ‘embed’) !== false){
  17. $code = str_replace(“/embed/”, “”, $parsed['path']);
  18. }//short link
  19. elseif($parsed['host'] == ‘youtu.be’){
  20. $code = str_replace(“/”, “”, $parsed['path']);
  21. }
  22. if($code){
  23. $final = str_replace(“{code}”, $code, $final);
  24. return $final;
  25. }else{
  26. return null;
  27. }
  28. }
  29. ?>

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

  • Wrapping Text using PHP
  • PHP 5.5 beta 4 is now available
  • Swapping Array Keys and Values
  • PHP Security
  • Working with Image Metadata in PHP
  • Converting Between Relative and Absolute File Path
  • Parsing File Paths with PHP
  • How to remove HTML Comments with PHP?
  • How to access .htaccess values?
  • Dealing With Common PHP Errors
  • Interview Questions and Answers for Freshers
  • Display numbers with ordinal suffix using PHP
  • Function to set COLLATION on database fields of Mysql
  • Read and write to remote files using PHP
  • Sharing PHP SESSION Variables between Multiple Subdomains
  • PHP 5.5.0 Alpha4 Development Preview Released
  • Check a string starts with http using PHP
  • Cross-Site Scripting Attacks (XSS)
  • PHP 5.4.11 and PHP 5.3.21 released!
  • PHP Memory Leak Issue
  •  

     

    1. November 7th, 2012 at 10:25 | #1

      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.

    2. free uk casino bets
      December 9th, 2012 at 20:05 | #2

      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

    1. No trackbacks yet.