Code snippets, tech tricks and other bits and bobs

« Back to blog

PHP - Convert youtu.be URLs to youtube.com

Youtube has introduced a new URL shorthand – youtu.be

For example youtu.be/DIArJjU8HjE takes you to

youtube.com/watch?v=DIArJjU8HjE&feature=youtu.be

Annoyingly this means that any users pasting a youtu.be URL into your video parsing scripts will be told it doesn’t work, so we’d best get updating those scripts!

Pop this in before you start processing the url, where $url is, not surprisingly, the url to be parsed.

//dMb 21/4/2011 Hack to handle youtu.be URLs dave@absolutedisaster.co.uk
$needle = '/^(http:\/\/)*(www\.)*(youtu\.be)\/([A-Za-z0-9]{11})$/';
preg_match($needle, $url, $result);
if($result[3] == 'youtu.be'){
    $url = 'http://www.youtube.com/watch?v=' . $result[4];
}
//dMb end hack

[update 20110720-1657] While implementing this and similar for grabbing youtube thumbnails today I suddenly though, what if youtube ever starts using https? Well, the odds may be slim, but the costs of allowing for it are negligible, so why take the risk?

//dMb 21/4/2011 Hack to handle youtu.be URLs dave@absolutedisaster.co.uk
//dMb 20/7/2011 Updated to allow for https
$needle = '/^(http(s?):\/\/)*(www\.)*(youtu\.be)\/([A-Za-z0-9]{11})$/';
preg_match($needle, $url, $result);
if($result[4] == 'youtu.be'){
    $url = 'http' . $result[2] . '://www.youtube.com/watch?v=' . $result[5];
}
//dMb end hack

[/update]

That particular link is the fantastic new video from my friends Six Toes – currently featured on the front of the Depeche Mode website.

May 04, 2011
benjaminfontain said...
quite good explanation for regular expressions
btw - you can use this htaccess on the root of every hosted domain
May 04, 2011
Dave Disaster said...
Not quite sure I follow you there Benjamin?
May 11, 2011
Robin Kearney said...
Dunno if it's useful for you but you can also say -mtime +1 day which searches for anything with a modification time of 1 day or more. Check the man page though because it is a little weird iirc, 1 day in your mind I think means 2 in finds opinion! Still useful though.
May 11, 2011
Dave Disaster said...
Hey Robin. Posterous seems to be posting comments to the wrong topics - am looking into this!

On that topic, yeah, finding within a fixed period is nice and simple. I had need to check for an absolute time, for which I found the syntax poorly explained, so thought it was worth noting for future reference...

Jun 16, 2011
Adele said...
Hi, thank you for this conversion.. It helps me.
Jun 16, 2011
Dave Disaster said...
Glad it is of use! And huzzah... Comments seem to be going to the correct entries now. What joy...