Embedding Mobile YouTube in Dabr / Twitter
I've decided to add a preview of YouTube videos into Dabr, the mobile Twitter service.
The code is fairly simple - although I still suck at regular expressions.
PHP
if (preg_match_all('#youtube.com/watch?v=([_-dw]+)#', $tmp, $matches, PREG_PATTERN_ORDER) > 0)
{
foreach ($matches[1] as $match)
{
$images[] = theme('external_link', "http://m.youtube.com/watch?v={$match}", "<img src='http://i.ytimg.com/vi/{$match}/1.jpg' class='twitpic' />");
}
}
Here's how it looks. A user writes a tweet which contains a YouTube URL

A thumbnail embedded in a tweet
The thumbnail is displayed and hyperlinked to the mobile version of YouTube

Pointing to Mobile YouTube
When clicked on, the user is taken straight to the video's page.

The Destination
There were three main issues with this code
- How do we extract the video's ID from the URL? YouTube video IDs contain alphanumeric character and the - and _ characters. They can also have other parameters passed. There can also be text after the URL. The regular expression above takes care of them.
- How do we get the thumbnail? Previously, I had been using the image URL given in the m.YouTube page - something like http://i.ytimg.com/vi/plvE4882B7Y/default.jpg?w=80&h=60 - however those URLs now need signing. So, using the YouTube API, I took a look at the Video Information XML file - http://gdata.youtube.com/feeds/api/videos/plvE4882B7Y - it showed that all videos have a full sized thumbnail - http://i.ytimg.com/vi/plvE4882B7Y/0.jpg and a mobile friendly thumbnail - http://i.ytimg.com/vi/plvE4882B7Y/1.jpg
- How do we link to the mobile version of YouTube? There are two ways to do this - either allow YouTube to detect the User-Agent and redirect based on that, or simply point to the mobile version. While a regular YouTube link looks like http://www.youtube.com/watch?v=plvE4882B7Y the mobile one simply substitutes www for m : http://m.youtube.com/watch?v=plvE4882B7Y
TODO
For phones which support playing YouTube videos inline (Android, some Nokias etc) I may actually embed the video, rather than just link to it. I may also detect Desktop Browsers and send them to the regular version of YouTube.
w is 'word characters' - it includes digits and the underscore. Your regex only needs to be [-w]+
joel says:
which folder exactly do u modify to add that code
No need to modify anything; the latest version of Dabr uses Embed.ly to help embed media.