Monday, September 21, 2009

Regex for a youtube video PHP

This post is about a regex for a youtube address as well as embedding it yourself, all in php.

First off, all youtube videos have the following address:
http://www.youtube.com/watch?v=XxXXxXXxXxX  <-- not a tested link

In each of those, you will find a v=11 character code. So what you need if a user gives you such a link for his video, you must extract the 11 char code of the string only. So the code to do that is

$link = $_POST["youtubelink"];

preg_match("/v\=([\-\w]+)/", $link, $matches);
$link = $matches[1];/*matches[0] includes the v= and you dont want that*/



To embed the video in your page, you can use the usual youtube embed code (even if the embedding is disabled, but your users should have it enabled unless you actually attract WMG to your site, in which case you should just ban them because they're retarded)
Here is the code:


$linkcode = $link;//11 char code

$arr[$i]["src"] ='<object height="344" width="425">
<param name="movie" value="http://www.youtube.com/v/'.$linkcode.'&hl=en&fs=1&" />
<param name="allowFullScreen" value="false" />
<param name="allowscriptaccess" value="always" />
<embed allowfullscreen="false" allowscriptaccess="always" height="344" src="http://www.youtube.com/v/'.$linkcode.'&hl=en&fs=1&" type="application/x-shockwave-flash" width="425" /> ';


You can always change options too, its just typical object/embed code :)

No comments:

Post a Comment