how to get Video id from url of youtube in php and cakephp
i have this url
http://youtu.be/JaFfJN_iKdA
how to get video id from it by regular expression
$url = "http://youtu.be/JaFfJN_iKdA";
if (preg_match('%(?:youtube\.com/(?:user/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $result)) {
$video_id = $result[1];
}
That will work for a bunch of common YT URL formats including the one you posted.
Instead of regular expressions, you could use parse_url()
function:
<?php
$url = parse_url("http://youtu.be/JaFfJN_iKdA");
echo substr($url["path"], 1);
you could use the library of http://autoembed.com/ it also covers 100 other video portals
after hard working ,i make a function for getting youtube info
function getYoutubeThumbnail($url)
{
if(preg_match('![?&]{1}v=([^&]+)!', $url . '&', $m))
{
$videoid = $m[1];
}
else if(preg_match('~/v/([0-9a-z_]+)~i', $url, $m))
{
$videoid = $m[1];
}
/* else if (preg_match('%(?:youtube\.com/(?:user/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $result))
{
$video_id = $result[1];
}*/
$youtube_thumbnail = 'http://img.youtube.com/vi/' . $videoid . '/default.jpg';
$c = curl_init();
$url = trim($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $url);
$contents = curl_exec($c);
curl_close($c);
$feed = "http://gdata.youtube.com/feeds/api/videos/".$videoid;
$newInfo = trim(@file_get_contents($feed));
preg_match('/<media:title(.*?)<\/media:title>/', $newInfo, $result);
$title = strip_tags($result[0]);
preg_match('/<media:keywords(.*?)<\/media:keywords>/', $newInfo, $result);
$desc = strip_tags(str_replace(",", "", $result[0]));
//embed path
$embed_path = "http://www.youtube.com/embed/".$videoid;
$youtube_info = array('videoid' => $videoid,'title' => $title, 'description' => $desc,'youtube_thumbnail' => $youtube_thumbnail,'embed_path' => $embed_path) ;
return $youtube_info;
}