Tuesday 30 April 2013

Youtube Embed code with URL parsing with REGEX validation

<?php

        if($_REQUEST['submit']){
        echo "Your submitted URL : ".$url = $_POST['link']."<br/>";

      /* regex check for youtube link */

 
      $rx = '~
       ^(?:https?://)?              # Optional protocol
       (?:www\.)?                  # Optional subdomain
       (?:youtube\.com|youtu\.be)  # Mandatory domain name
       /
       (?:watch\?v=)?              # Optional
       ([^&]+)           # URI with video id as capture group 1
       ~x';

      $has_match = preg_match($rx, $url);
      if($has_match){
      echo "matched";    //if url matched
      echo "<br/>";


      /* Embed code goes here */   

     $url = $_POST['link'];
     //$url='www.youtube.com/watch?v=ntHYVy7lWoc'; // example link 1
     //$url='http://youtu.be/Z19vR1GldRI'; // example link 1
 

      $url = substr($url,-11); // to get the last 11 character from the link to put in our embed code

     echo <<<EOF
    <object width="700" height="400">
    <param name="movie" value="http://www.youtube.com/v/{$url}&hl=en&fs=1"></param>
    <param name="wmode" value="transparent"></param>   
    <param name="allowFullScreen" value="true"></param>
    <param name="allowscriptaccess" value="always"></param>
    <embed src="http://www.youtube.com/v/{$url}&hl=en&fs=1" wmode="transparent"
           type="application/x-shockwave-flash"
           allowscriptaccess="always"
           allowfullscreen="true"
           width="700"
           height="400"></embed>
</object>
EOF;

    }
    else
    {
    echo "Enter valid url";        // if url doesn't match
    }
}
?>

<form name="form" method="post">
<input type="text" value="" name="link" />
<input type="submit" value="submit" name="submit" />
</form>