How to replace Youtube urls in text with embeded code (in PHP)? - php

This is what I've got so far:
<?php
$content = "word1 http://www.youtube.com/watch?v=yqfKe-67foQ&feature=related word2 http://www.youtube.com/watch?v=2vq7gDEn99Y&feature=related word3 http://www.youtube.com/watch?v=nW5HxgMYRto\nhttp://www.youtube.com/watch?v=8Uc2lpH0iZ0&feature=fvhl";
$pattern = '/http:\/\/www\.youtube\.com\/watch\?(.*)v=([a-zA-Z0-9_\-]+)(\S*)/i';
$replace = '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/$2&hl=en_US&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/$2&hl=en_US&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>';
$content = preg_replace($pattern, $replace, $content);
echo $content;
?>
I honestly have no idea why it doesn't work. Some help would be appreciated. Thanks.

You just have to make * non-greedy:
http:\/\/www\.youtube\.com\/watch\?(.*?)v=([a-zA-Z0-9_\-]+)(\S*)
See "Watch out for greediness".

Try this simple function for URL replacement
function youtube($string)
{
return preg_replace(
'#(http://(www.)?youtube.com)?/(v/|watch\?v\=)([-|~_0-9A-Za-z]+)&?.*?#i',
'<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/$4" frameborder="0" allowfullscreen></iframe>',
$string
);
}
echo youtube('http://www.youtube.com/watch?v=VWsjWCt1PsQ');
echo youtube('http://youtube.com/watch?v=VWsjWCt1PsQ');
echo youtube('http://youtube.com/v/VWsjWCt1PsQ');
echo youtube('http://www.youtube.com/v/VWsjWCt1PsQ');

I would just create a string with a configured embed code. Link attribute could be #LINK#, width="#WIDTH#". Than replace all parameters with your own value. It could be much more comfortable to use. Or you can simply use a youtube embed code generator for that.

Related

How to make direct youtube video url work not embeded?

How to make youtube video work on site without embeded code? I mean direct code as: https://www.youtube.com/watch?v=ouDmKW1FGjo. I want the user to paste direct video url into a field VIDEO_LINK not the embeded code. How can I do that? Only embeded link works on the below code not the direct link.
<iframe width="100%" height="550" src="<?php the_field('video_link') ?>" frameborder="0" allowfullscreen></iframe>
Use the following code to get video key (assuming the URL is https://www.youtube.com/watch?v=ouDmKW1FGjo):
<?php
$video_url=get_field('video_link');
$url = urldecode(rawurldecode($video_url));
preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $matches);
// Get key of youtube by preg_match and put it in iframe
$videoKey= $matches[1];
?>
<iframe width="100%" height="550" src="https://www.youtube.com/embed/<?php echo $videoKey ;?>" frameborder="0" allowfullscreen></iframe>
You may use this function to convert Youtube URL to embeded code:
function get_youtube_embed($youtube_url, $width=560, $height=315)
{
$height = (int)$height;
$width = (int)$width;
$embed_html = '';
$parts = parse_url($youtube_url);
if(isset($parts['query'])) {
parse_str($parts['query'], $query);
if(isset($query['v'])) {
$embed_html = '<iframe width="'.$width.'" height="'.$height.'" src="https://www.youtube.com/embed/'.$query['v'].'" frameborder="0" allowfullscreen></iframe>';
}
}
return $embed_html;
}

PHP preg_replace not replacing anything

Can someone tell me why when I run this code the preg_replace function seems like it does nothing?
<?php
$string = 'waka http://video.webmfiles.org/big-buck-bunny_trailer.webm waka';
$search = '#http\:\/\/.\.webm #';
$replace = '<video width="320" height="240" controls><source src="$1" type="video/webm"></video>';
$url = preg_replace($search,$replace,$string);
echo $url;
?>
Is my $search string wrong? If so, how can I fix it? It's suppose to replace strings starting in http:// and ending in .webm and surround them with the html code needed to play the .webm video.
Here's how I'd do this...
$string = 'waka http://video.webmfiles.org/big-buck-bunny_trailer.webm waka';
$search = '/(https?\:\/\/.+?\.webm)\h/';
$replace = '<video width="320" height="240" controls><source src="$1" type="video/webm"></video> ';
$url = preg_replace($search,$replace,$string);
echo $url;
Output:
waka <video width="320" height="240" controls><source src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" type="video/webm"></video> waka
Regex101 demo: https://regex101.com/r/qR1xJ7/2
I ended up figuring it out. I'm now using:
$search = '#http:\/\/([^\']+)\.webm #';

Searching YouTube and displaying first video in PHP, advice needed?

I'm not sure when, but at some point my YouTube searching method stopped working, it has worked for years but both the API and the preferred method of displaying embedded video has changed. I've looked at the official Google docs and I have the option of using Zend or the currently in development Version 3 of the Google API, these are a lot larger codebases than what I was currently using.
I've tried debugging my code and may eventually get it working again, should I just scrap it and integrate the more official PHP codebase into my project. This was is where my method sits, it finds data, but I don't seem to display any videos...
public function embeddableVideoClipFor($searchString)
{
// Previous experience revealed that video search is not perfect, but we're just going to giver and create an embedded player with the
// top result or return NULL
// I used this as a guide to build my embedded player http://code.google.com/apis/youtube/youtube_player_demo.html
$embeddableVideoClipHTML = NULL;
// Further details on searching YouTube http://www.ibm.com/developerworks/xml/library/x-youtubeapi/
// This was working well for over two years but now I'm getting no videos, I may have been throttled or more likely the API has changed...
// Before switching to Zend or going to switch to version 3.0 of Google/YouTube API I should try and debug...
$vq = $searchString;
$vq = preg_replace('/[[:space:]]+/', ' ', trim($vq));
$vq = urlencode($vq);
$feedURL = 'http://gdata.youtube.com/feeds/api/videos?q=' . $vq . '&safeSearch=none&orderby=viewCount&v=2'; // Added version two tag...
print_r($feedURL);
// read feed into SimpleXML object
try
{
$youTubeXML = simplexml_load_file($feedURL);
}
catch(Exception $e)
{
// This rarely throws an error, but when it does, I just want to pretend I can't find a video clip
$youTubeXML = NULL;
}
print("<pre>");
print_r($youTubeXML);
print("</pre>");
if(($youTubeXML != NULL) && ( ! empty($youTubeXML->entry->link[0]['href'])))
{
$videoLink = $youTubeXML->entry->link[0]['href']; // This is not enough, I need to trim the beginning and end off this to just get the video code
$trimedURL = str_replace('http://www.youtube.com/watch?v=', '' , $videoLink);
$videoCode = str_replace('&feature=youtube_gdata', '', $trimedURL);
// $embeddableVideoClipHTML = '<object style="height: 390px; width: 640px"><param name="movie" value="http://www.youtube.com/v/' . $videoCode . '"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><embed src="http://www.youtube.com/v/' . $videoCode . '?version=3" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="390"></object>';
// $embeddableVideoClipHTML = '<iframe id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube.com/embed/' . $videoCode . '"frameborder="0" allowfullscreen>';
// Version 3
$embeddableVideoClipHTML = '<object width="640" height="360"><param name="movie" value="https://www.youtube.com/v/' . $videoCode . '?version=3"></param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param><embed src="https://www.youtube.com/v/' . $videoCode . '?version=3" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="360"></embed></object>';
}
return $embeddableVideoClipHTML;
}
I'm not sure why, because I did try it, but switching to the iFrame, ie this line of code:
// $embeddableVideoClipHTML = '<iframe id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube.com/embed/' . $videoCode . '"frameborder="0" allowfullscreen>';
Works now, but I still wonder if I should jump through hoops to use one of the more official PHP frameworks, I really only use this one method to access the Google/YouTube api, it isn't a big part of my mashup, but I like it for movie trailers and song lyric quotations.

youtube autoplay is not working with iframe

i have php function which generate youtube code to display video but auto play is not working properly
function get_youtube_embed($youtube_video_id = 0, $auto = 0) {
$embed_code = "";
if ($auto == 1) {
$embed_code = '<iframe width="589" height="342" src="http://www.youtube.com/embed/' . $youtube_video_id . '?autoplay=1" frameborder="0" allowfullscreen></iframe>';
}
else {
$embed_code = '<iframe width="589" height="342" src="http://www.youtube.com/embed/' . $youtube_video_id . '" frameborder="0" allowfullscreen></iframe>';
}
return $embed_code;
}
Thanks
Your code is alright, try doing it by hand, without Javascript. Most likely that the way to set autoplay is wrong in your code.
It appears that the autoplay does not always work in the newer
At the bottom of the embed option section on the youtube site, there is a checkbox allowing you to use the old code. Use this as your base.
Your code should look something like this:
$embed_code = '<object width="420" height="345"><param name="movie" value="http://www.youtube.com/v/' . $youtube_video_id . '?version=3&hl=en_US&rel=0&autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' . $youtube_video_id . '?version=3&hl=en_US&rel=0&autoplay=1" type="application/x-shockwave-flash" width="420" height="345" allowscriptaccess="always" allowfullscreen="true"></embed></object>';
see: http://www.google.com/support/youtube/bin/answer.py?answer=171780&expand=UseOldEmbedCode#oldcode

calling function inside preg_replace thats inside a function

I have some code with the a structure similar to this
function bbcode($Text)
{ //$Text = preg_replace("/\[video\](.+?)\[\/video\]/",embed_video($1), $Text);
return $Text;}
function embed_video($url){
if (preg_match("/http:\/\/www.youtube.com\/watch\?v=([0-9a-zA-Z-_]*)(.*)/i", $url, $matches)) {
return '<object width="425" height="350">'.
'<param name="movie" value="http://www.youtube.com/v/'.$matches[1].'" />'.
'<param name="wmode" value="transparent" />'.
'<embed src="http://www.youtube.com/v/'.$matches[1].'&autoplay="0" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350" />'.
'</object>';
}
return $url;
}
$lolcakes = "[video]http://youtube.com/id/xxxxxxpron[/video]";
$lolcakesconverted = bbcode($lolcakes);
The problem is it spits an error back at me.
Parse error: syntax error, unexpected T_LNUMBER, expecting T_VARIABLE or '$'
Have any ideas on how i can call embed_video inside of the preg_replace of the bbcode function?
Thanks!
try preg_replace_callback
return preg_replace_callback("/\[video\](.+?)\[\/video\]/", 'embed_video', $Text);
function embed_video($matches)
{
return $matches[1] . 'foo';
}
You can use the "e" modifier on preg_replace() (see Pattern Modifiers)
return preg_replace("/\[video\](.+?)\[\/video\]/e", "embed_video('$1')", $Text);
which tells preg_replace() to treat the second parameter as PHP code.

Categories