在 PHP 字符串中查找 youtube 链接并将其转换为嵌入代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19050890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:43:38  来源:igfitidea点击:

Find youtube Link in PHP string and Convert it into embed code?

phpstringreplaceyoutubefind

提问by Hassan Sardar

Find a Youtubevideo linkin PHP Stringand convertit into Embed Code?

查找的Youtube视频 链接PHP字符串,并转换嵌入代码

Embed Code:

嵌入代码:

<iframe width="420" height="315" src="//www.youtube.com/embed/0GfCP5CWHO0" frameborder="0" allowfullscreen></iframe>

PHP Code / String:

PHP代码/字符串:

<?php echo $post_details['description']; ?>

Youtube Link:

优酷链接:

http://www.youtube.com/watch?v=0GfCP5CWHO0

回答by Joran Den Houting

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/\" frameborder=\"0\" allowfullscreen></iframe>",$post_details['description']);

回答by Syone

A little enhancement of Joran's solution to handle also youtube short URL format:

Joran 处理 youtube 短 URL 格式的解决方案的一些增强:

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/\" allowfullscreen></iframe>",
        $string
    );
}

You can test this function online here

您可以在此处在线测试此功能

回答by Ahmad Mobaraki

There are two types of youtube link for one video:

一个视频有两种类型的 YouTube 链接:

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 :

$link1 或 $link2 的输出将是相同的:

 $output1 = getYoutubeEmbedUrl($link1);
 $output2 = getYoutubeEmbedUrl($link2);
 // output for both:  https://www.youtube.com/embed/NVcpJZJ60Ao

Now you can use the output in iframe!

现在您可以在 iframe 中使用输出了!

回答by iniravpatel

A quick function for generating Embed url link of any of the FB/vimeo/youtube videos.

用于生成任何 FB/vimeo/youtube 视频的嵌入 url 链接的快速功能。

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;
}

回答by Luke Stevenson

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.

我知道这是一个旧线程,但是对于遇到此挑战并寻求帮助的任何人,我在 GitHub - Embera上找到了一个 PHP 类。

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!

基本上是一个 oembed 库,它将任何字符串中的 YouTube URL 转换为关联的 iframe 元素。我正在使用它,并将继续在任何地方使用它!

回答by Sagive SEO

I think a safe, super simple way to get the id
which is kinda bulletproof is to simply use the URL structure.

我认为获取
有点防弹的 id 的一种安全、超级简单的方法是简单地使用 URL 结构。

function getYoutubeEmbedUrl($url){

    $urlParts   = explode('/', $url);
    $vidid      = explode( '&', str_replace('watch?v=', '', end($urlParts) ) );

    return 'https://www.youtube.com/embed/' . $vidid[0] ;
}

回答by Mahesh Yadav

Below will work for all type of YouTube URLs.

以下适用于所有类型的 YouTube 网址。

preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);

$youtube_id = $match[1];

回答by Shakil Hossain

<?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> 

回答by Tim Nikischin

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:

好吧,您需要先过滤掉youtube链接并将它们放入数组中。接下来,您需要找出网址的视频 ID,这很容易。使用这个脚本:

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 ;)

你当然也可以使用 PHP 函数,但我这里只是使用 JS 从 URL 中获取 id。也许这有帮助;)

With the video id you can embed the video ;)

使用视频 ID,您可以嵌入视频 ;)

回答by Michael Giovanni Pumo

If the string is from user input, or in anyway unpredictable, then forget using RegEx...seriously. It will open a can of worms for you.

如果字符串来自用户输入,或者以任何方式不可预测,那么请忘记使用 RegEx...认真地。它会为你打开一罐蠕虫。

Instead, try to look into using a HTML parser to extract the URL's based on certain rules and selectors.

相反,尝试使用 HTML 解析器根据某些规则和选择器提取 URL。

I mainly use ColdFsuion / Java and JSoup is amazing for this kind of thing, with a whole lot more ease and security too.

我主要使用 ColdFsuion / Java,而 JSoup 对这种事情非常棒,而且更容易和安全。

http://jsoup.org/

http://jsoup.org/

It seems, in PHP, you could use something like this:

看来,在 PHP 中,你可以使用这样的东西:

http://code.google.com/p/phpquery/

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.

我很想提供一个代码示例,但我对 PHP 还不够了解。但是试一试。

Mikey.

米奇。