Related
I'm trying to extract the facebook user id of html, is it possible?
I'm trying in this way but does not return a result.
function get_subs($url){
$url = 'http://www.facebook.com/'.$url.'';
$url = get_data($url);
preg_match('/"profile_id": (.*?),/',$url,$result);
$return = preg_replace("/[^\d]/", "", $result[1]);
return $return;
}
$key = get_subs($url)
$url is profile name e.g 'gr.adriannicu' now i need extract id from html.
This method works on instragram .
function get_followers($url){
$url = 'http://instagram.com/'.$url.'/';
$url = get_data($url);
preg_match('/followed_by":(.*?),/',$url,$result);
$return = preg_replace("/[^\d]/", "", $result[1]);
return $return;
}
function return numbers of followers. I trying use this same method to extract facebook id based by profile name .
Find a Youtube video link in PHP String and convert it into Embed Code?
Embed Code:
<iframe width="420" height="315" src="//www.youtube.com/embed/0GfCP5CWHO0" frameborder="0" allowfullscreen></iframe>
PHP Code / String:
<?php echo $post_details['description']; ?>
Youtube Link:
http://www.youtube.com/watch?v=0GfCP5CWHO0
Try this:
preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i","<iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>",$post_details['description']);
There are two types of youtube link for one video:
Example:
$link1 = 'https://www.youtube.com/watch?v=NVcpJZJ60Ao';
$link2 = 'https://www.youtu.be/NVcpJZJ60Ao';
This function handles both:
function getYoutubeEmbedUrl($url)
{
$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_-]+)\??/i';
$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))([a-zA-Z0-9_-]+)/i';
if (preg_match($longUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
if (preg_match($shortUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
return 'https://www.youtube.com/embed/' . $youtube_id ;
}
The output of $link1 or $link2 would be the same :
$output1 = getYoutubeEmbedUrl($link1);
$output2 = getYoutubeEmbedUrl($link2);
// output for both: https://www.youtube.com/embed/NVcpJZJ60Ao
Now you can use the output in iframe!
A little enhancement of Joran's solution to handle also youtube short URL format:
function convertYoutube($string) {
return preg_replace(
"/\s*[a-zA-Z\/\/:\.]*youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i",
"<iframe src=\"//www.youtube.com/embed/$2\" allowfullscreen></iframe>",
$string
);
}
You can test this function online here
A quick function for generating Embed url link of any of the FB/vimeo/youtube videos.
public function generateVideoEmbedUrl($url){
//This is a general function for generating an embed link of an FB/Vimeo/Youtube Video.
$finalUrl = '';
if(strpos($url, 'facebook.com/') !== false) {
//it is FB video
$finalUrl.='https://www.facebook.com/plugins/video.php?href='.rawurlencode($url).'&show_text=1&width=200';
}else if(strpos($url, 'vimeo.com/') !== false) {
//it is Vimeo video
$videoId = explode("vimeo.com/",$url)[1];
if(strpos($videoId, '&') !== false){
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://player.vimeo.com/video/'.$videoId;
}else if(strpos($url, 'youtube.com/') !== false) {
//it is Youtube video
$videoId = explode("v=",$url)[1];
if(strpos($videoId, '&') !== false){
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://www.youtube.com/embed/'.$videoId;
}else if(strpos($url, 'youtu.be/') !== false){
//it is Youtube video
$videoId = explode("youtu.be/",$url)[1];
if(strpos($videoId, '&') !== false){
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://www.youtube.com/embed/'.$videoId;
}else{
//Enter valid video URL
}
return $finalUrl;
}
Example:
$link1 = getEmbedUrl('https://www.youtube.com/watch?v=BIjqw7zuEVE');
$link2 = getEmbedUrl('https://vimeo.com/356810502');
$link3 = getEmbedUrl('https://example.com/link/12345');
Function:
function getEmbedUrl($url) {
// function for generating an embed link
$finalUrl = '';
if (strpos($url, 'facebook.com/') !== false) {
// Facebook Video
$finalUrl.='https://www.facebook.com/plugins/video.php?href='.rawurlencode($url).'&show_text=1&width=200';
} else if(strpos($url, 'vimeo.com/') !== false) {
// Vimeo video
$videoId = isset(explode("vimeo.com/",$url)[1]) ? explode("vimeo.com/",$url)[1] : null;
if (strpos($videoId, '&') !== false){
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://player.vimeo.com/video/'.$videoId;
} else if (strpos($url, 'youtube.com/') !== false) {
// Youtube video
$videoId = isset(explode("v=",$url)[1]) ? explode("v=",$url)[1] : null;
if (strpos($videoId, '&') !== false){
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://www.youtube.com/embed/'.$videoId;
} else if(strpos($url, 'youtu.be/') !== false) {
// Youtube video
$videoId = isset(explode("youtu.be/",$url)[1]) ? explode("youtu.be/",$url)[1] : null;
if (strpos($videoId, '&') !== false) {
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://www.youtube.com/embed/'.$videoId;
} else if (strpos($url, 'dailymotion.com/') !== false) {
// Dailymotion Video
$videoId = isset(explode("dailymotion.com/",$url)[1]) ? explode("dailymotion.com/",$url)[1] : null;
if (strpos($videoId, '&') !== false) {
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://www.dailymotion.com/embed/'.$videoId;
} else{
$finalUrl.=$url;
}
return $finalUrl;
}
I know this is an old thread, but for anyone having this challenge and looking for assistance, I found a PHP Class on GitHub - Embera.
Basically an oembed library which converts YouTube URLs in any string into the associated iframe element. I'm using it, and will continue to use it everywhere!
I think a safe, super simple way to get the id
which is kinda bulletproof is to simply use the URL structure.
function getYoutubeEmbedUrl($url){
$urlParts = explode('/', $url);
$vidid = explode( '&', str_replace('watch?v=', '', end($urlParts) ) );
return 'https://www.youtube.com/embed/' . $vidid[0] ;
}
Below will work for all type of YouTube URLs.
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
$youtube_id = $match[1];
<?php
$url = 'https://www.youtube.com/watch?v=u9-kU7gfuFA';
preg_match('/[\\?\\&]v=([^\\?\\&]+)/', $url, $matches);
$id = $matches[1];
$width = '800px';
$height = '450px'; ?>
<iframe id="ytplayer" type="text/html" width="<?php echo $width ?>" height="<?php echo $height ?>"
src="https://www.youtube.com/embed/<?php echo $id ?>?rel=0&showinfo=0&color=white&iv_load_policy=3"
frameborder="0" allowfullscreen></iframe>
Another simple alternative would be using parse_url and parse_str functions.
function getYoutubeEmbedUrl ($url) {
$parsedUrl = parse_url($url);
# extract query string
parse_str(#$parsedUrl['query'], $queryString);
$youtubeId = #$queryString['v'] ?? substr(#$parsedUrl['path'], 1);
return "https://youtube.com/embed/{$youtubeId}";
}
Lets say we have these two links:
$link1 = 'https://www.youtube.com/watch?v=NVcpJZJ60Ao';
$link2 = 'https://www.youtu.be/NVcpJZJ60Ao';
getYoutubeEmbedUrl($link1); // https://youtube.com/embed/NVcpJZJ60Ao
getYoutubeEmbedUrl($link2); // https://youtube.com/embed/NVcpJZJ60Ao
Explanation
parse_url function will extract link into 4 components: scheme, host, path, and query (see docs).
parse_url($link1);
// output
[
"scheme" => "https",
"host" => "www.youtube.com",
"path" => "/watch",
"query" => "v=NVcpJZJ60Ao",
]
The output of $link2 would be:
parse_url($link2);
// output
[
"scheme" => "https",
"host" => "www.youtu.be",
"path" => "/NVcpJZJ60Ao",
]
And parse_str will convert query string into an array (see docs).
parse_str('v=NVcpJZJ60Ao', $output);
// value of variable $output
[
"v" => "NVcpJZJ60Ao",
]
Well, you need to filter out the youtube links first and put them into an array.
Next you need to find out the video id of the url which is very easy. Use this script:
function getIDfromURL() {
var video_url = document.getElementById('url').value;
var video_id = video_url.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if (ampersandPosition != -1) { video_id = video_id.substring(0, ampersandPosition); }
document.getElementById('url').value=video_id;
}
You can of course use a PHP function as well, but I just used JS here to get the id from the URL. Maybe that helped anyways ;)
With the video id you can embed the video ;)
If the string is from user input, or in any way unpredictable, then forget using RegEx...seriously. It will open a can of worms for you.
Instead, try to look into using a HTML parser to extract the URL's based on certain rules and selectors.
I mainly use ColdFsuion / Java and JSoup is amazing for this kind of thing, with a whole lot more ease and security too.
http://jsoup.org/
It seems, in PHP, you could use something like this:
http://code.google.com/p/phpquery/
I'd love to give a code sample, but I don't know PHP well enough. But give it a go.
Mikey.
Try this too:
$text = "is here the text to replace";
function replace_iframe($id_video) {
return '<iframe height="315" width="100%" src="https://www.youtube.com/embed/'.$id_video[1].'" frameborder="0" allowfullscreen></iframe>';
}
echo preg_replace_callback("/\s*[a-zA-Z\/\/:\.]*(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i", 'replace_iframe', $text);
I am currently writing a webapp in which some pages are heavily reliant on being able to pull the correct youtube video in - and play it. The youtube URLS are supplied by the users and for this reason will generally come in with variants one of them may look like this:
http://www.youtube.com/watch?v=y40ND8kXDlg
while the other may look like this:
http://www.youtube.com/watch/v/y40ND8kXDlg
Currently I am able to pull the ID from the latter using the code below:
function get_youtube_video_id($video_id)
{
// Did we get a URL?
if ( FALSE !== filter_var( $video_id, FILTER_VALIDATE_URL ) )
{
// http://www.youtube.com/v/abcxyz123
if ( FALSE !== strpos( $video_id, '/v/' ) )
{
list( , $video_id ) = explode( '/v/', $video_id );
}
// http://www.youtube.com/watch?v=abcxyz123
else
{
$video_query = parse_url( $video_id, PHP_URL_QUERY );
parse_str( $video_query, $video_params );
$video_id = $video_params['v'];
}
}
return $video_id;
}
How can I deal with URLS that use the ?v version rather than the /v/ version?
Like this:
$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
$video_id = explode("?v=", $link);
$video_id = $video_id[1];
Here is universal solution:
$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0&lololo";
$video_id = explode("?v=", $link); // For videos like http://www.youtube.com/watch?v=...
if (empty($video_id[1]))
$video_id = explode("/v/", $link); // For videos like http://www.youtube.com/watch/v/..
$video_id = explode("&", $video_id[1]); // Deleting any other params
$video_id = $video_id[0];
Or just use this regex:
(\?v=|/v/)([-a-zA-Z0-9]+)
<?php
// Here is a sample of the URLs this regex matches: (there can be more content after the given URL that will be ignored)
// http://youtu.be/dQw4w9WgXcQ
// http://www.youtube.com/embed/dQw4w9WgXcQ
// http://www.youtube.com/watch?v=dQw4w9WgXcQ
// http://www.youtube.com/?v=dQw4w9WgXcQ
// http://www.youtube.com/v/dQw4w9WgXcQ
// http://www.youtube.com/e/dQw4w9WgXcQ
// http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ
// http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ
// http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
// http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
// It also works on the youtube-nocookie.com URL with the same above options.
// It will also pull the ID from the URL in an embed code (both iframe and object tags)
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
$youtube_id = $match[1];
?>
<?php
$your_url='https://www.youtube.com/embed/G_5-SqD2gtA';
function get_youtube_id_from_url($url)
{
if (stristr($url,'youtu.be/'))
{preg_match('/(https:|http:|)(\/\/www\.|\/\/|)(.*?)\/(.{11})/i', $url, $final_ID); return $final_ID[4]; }
else
{#preg_match('/(https:|http:|):(\/\/www\.|\/\/|)(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})/i', $url, $IDD); return $IDD[5]; }
}
echo get_youtube_id_from_url($your_url)
?>
Try:
function youtubeID($url){
$res = explode("v",$url);
if(isset($res[1])) {
$res1 = explode('&',$res[1]);
if(isset($res1[1])){
$res[1] = $res1[0];
}
$res1 = explode('#',$res[1]);
if(isset($res1[1])){
$res[1] = $res1[0];
}
}
return substr($res[1],1,12);
return false;
}
$url = "http://www.youtube.com/watch/v/y40ND8kXDlg";
echo youtubeID($url1);
Should work for both
Okay, this is a much better answer than my previous:
$link = 'http://www.youtube.com/watch?v=oHg5SJYRHA0&player=normal';
strtok($link, '?');
parse_str(strtok(''));
echo $v;
It's might be good to have this in a function to keep the new variables out of the global scope (unless you want them there, obviously).
This may not be in use still, but there might be other people looking for an answer, so, to get a YouTube ID from a URL.
P.S: This works for all types of URL, I've tested it;
Function getYouTubeID($URL){
$YouTubeCheck = preg_match('![?&]{1}v=([^&]+)!', $URL . '&', $Data);
If($YouTubeCheck){
$VideoID = $Data[1];
}
Return $VideoID;
}
Or just use the preg_match function itself;
If(preg_match('![?&]{1}v=([^&]+)!', $URL . '&', $Data)){
$VideoID = $Data[1];
}
Hope this helps someone :)!
Simplest method I know with YouTube.
function GetYouTubeId($url)
{
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
$youtube_id = $match[1];
return $youtube_id;
}
$parts = explode('=', $link);
// $parts[1] will y40ND8kXDlg
This example works only if there's one '=' in the URL. Ever likely to be more?
i just would search for the last "/" or the last "=". After it you find always the video-id.
preg_match("#([\w\d\-]){11}#is", 'http://www.youtube.com/watch?v=y40ND8kXDlg', $matches);
echo $matches[1];
This is best way to get youtube vedio id , Or any field in url , but you must change index (V) from $ID_youtube['v'] to anything you want.
function getID_youtube($url)
{
parse_str(parse_url($url, PHP_URL_QUERY), $ID_youtube);
return $ID_youtube['v'];
}
<?php
$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
$video_id = str_replace('http://www.youtube.com/watch?v=', '', $link);
echo $video_id;
?>
Output:
oHg5SJYRHA0
Source
<?php
$url = "https://www.youtube.com/watch?v=uKW_FPsFiB8&feature=related";
parse_str( parse_url( $url, PHP_URL_QUERY ), $vid );
echo $vid['v'];
?>
Output: uKW_FPsFiB8
This will work for urls like https://www.youtube.com/watch?v=uKW_FPsFiB8&feature=related or https://www.youtube.com/watch?v=vzH8FH1HF3A&feature=relmfu or only https://www.youtube.com/watch?v=uKW_FPsFiB8
All YouTube video ids are 11 characters of length. I wrote Regex based it:
<?php
$url = "https://www.youtube.com/watch?v=gooWdc6kb80";
preg_match('/(?:\/|=)(.{11})(?:$|&|\?)/', $url, $matches);
echo $matches[1];
?>
It can match different YouTube video formats:
// http://youtu.be/dQw4w9WgXcQ
// http://www.youtube.com/embed/dQw4w9WgXcQ
// http://www.youtube.com/watch?v=dQw4w9WgXcQ
// http://www.youtube.com/?v=dQw4w9WgXcQ
// http://www.youtube.com/v/dQw4w9WgXcQ
// http://www.youtube.com/e/dQw4w9WgXcQ
// http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ
// http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ
// http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
// http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
// https://www.youtube.com/embed/dQw4w9WgXcQ?feature=oembed
// https://www.youtube.com/embed/dQw4w9WgXcQ?start=16&feature=oembed
I am trying to search youtube through the api and then save the search to a variable and then echo. Having trouble getting this to work! I have included the entire code in html. I'm not sure if it has to do with loading the youtube script library or more of a syntax error. Thanks!
<html>
<body>
<?php
$params="puppy";
function youtube_find_video($params)
{
str_replace("'", "", $params);
$q = preg_replace('/[[:space:]]/', '/', trim($params));
$q = utf8_decode(utf8_encode($q));
$replacements = array(',', '?', '!', '.');
$q = str_replace($replacements, "", $q);
$feedURL = "http://gdata.youtube.com/feeds/api/videos/-/{$q}?orderby=relevance&max-results=1";
$sxml = simplexml_load_file($feedURL);
if(!$sxml)
{
return false;
}
else{
$entry = $sxml->entry;
if(!$entry)
{
return false;
}
// get nodes in media: namespace for media information
$media = $entry->children('http://search.yahoo.com/mrss/');
if($media)
{
// get video player URL
$attrs = $media->group->player->attributes();
$url = $attrs['url'];
if(!$url)
{
return false;
break;
}
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
$watch['id'] = $my_array_of_vars['v'];
// get video name
$watch['name'] = $media->group->title;
// get <yt:duration> node for video length[minute]
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
$watch['length'] = sprintf("%0.2f", $attrs['seconds']/60);
$watch = simplexml_kurtul($watch);
return $watch;
echo $watch;
}
else
{
return false;
}
}
}
youtube_find_video();
?>
</body>
</html>
You are calling youtube_find_video() without the $params. Change the last line of PHP to:
youtube_find_video($params);
Also please give the errors you get. It's impossible to help without knowing what's wrong.
Example:
http://www.dailymotion.com/video/x4xvnz_the-funny-crash-compilation_fun
How do I get x4xvnz?
You can use basename [docs] to get the last part of the URL and then strtok [docs] to get the ID (all characters up to the first _):
$id = strtok(basename($url), '_');
/video\/([^_]+)/
should do the trick. This grabs in the first capture all text after video/ up till the first _.
preg_match('#<object[^>]+>.+?http://www.dailymotion.com/swf/video/([A-Za-z0-9]+).+?</object>#s', $dailymotionurl, $matches);
// Dailymotion url
if(!isset($matches[1])) {
preg_match('#http://www.dailymotion.com/video/([A-Za-z0-9]+)#s', $dailymotionurl, $matches);
}
// Dailymotion iframe
if(!isset($matches[1])) {
preg_match('#http://www.dailymotion.com/embed/video/([A-Za-z0-9]+)#s', $dailymotionurl, $matches);
}
$id = $matches[1];
I use this:
function getDailyMotionId($url)
{
if (preg_match('!^.+dailymotion\.com/(video|hub)/([^_]+)[^#]*(#video=([^_&]+))?|(dai\.ly/([^_]+))!', $url, $m)) {
if (isset($m[6])) {
return $m[6];
}
if (isset($m[4])) {
return $m[4];
}
return $m[2];
}
return false;
}
It can handle various urls:
$dailymotion = [
'http://www.dailymotion.com/video/x2jvvep_coup-incroyable-pendant-un-match-de-ping-pong_tv',
'http://www.dailymotion.com/video/x2jvvep_rates-of-exchange-like-a-renegade_music',
'http://www.dailymotion.com/video/x2jvvep',
'http://www.dailymotion.com/hub/x2jvvep_Galatasaray',
'http://www.dailymotion.com/hub/x2jvvep_Galatasaray#video=x2jvvep',
'http://www.dailymotion.com/video/x2jvvep_hakan-yukur-klip_sport',
'http://dai.ly/x2jvvep',
];
Check out my github (https://github.com/lingtalfi/video-ids-and-thumbnails/blob/master/testvideo.php), I provide functions to get ids (and also thumbnails) from youtube, vimeo and dailymotion.
<?php
$output = parse_url("http://www.dailymotion.com/video/x4xvnz_the-funny-crash-compilation_fun");
// The part you want
$url= $output['path'];
$parts = explode('/',$url);
$parts = explode('_',$parts[2]);
echo $parts[0];
http://php.net/manual/en/function.parse-url.php