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*/