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

28

PHP 字符串 中查找 YouTube 视频 的链接,并将其转换为 嵌入代码

嵌入代码:

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

PHP 代码/字符串:

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

Youtube链接:

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

1
YouTube的字符串长什么样? - Amal Murali
@AmalMurali 帖子已更新,请查看。 - Hassan Sardar
可能重复:https://dev59.com/xWPVa4cB1Zd3GeqP5mwn https://dev59.com/zW_Xa4cB1Zd3GeqP3KHC http://stackoverflow.com/questions/4713311/hyperlink-youtube-to-embed-code - Amal Murali
1
我查看时,这个帖子为什么会有+2和3个收藏?这是一种新的评论垃圾邮件吗? - Matt Humphrey
14个回答

44

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

例如:

$link1 = 'https://www.youtube.com/watch?v=NVcpJZJ60Ao';
$link2 = 'https://www.youtu.be/NVcpJZJ60Ao';

此函数同时处理以下两种情况:

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 ;
}
$link1وˆ–$link2çڑ„输ه‡؛ه°†وک¯ç›¸هگŒçڑ„ï¼ڑ
 $output1 = getYoutubeEmbedUrl($link1);
 $output2 = getYoutubeEmbedUrl($link2);
 // output for both:  https://www.youtube.com/embed/NVcpJZJ60Ao

现在你可以在iframe中使用该输出!


在URL类似于https://www.youtube.com/watch?time_continue=1&v=NVcpJZJ60Ao的情况下会发生什么? - cch
1
我在这里添加了一个连字符,以便使其与我的某些共享链接配合使用: $shortUrlRegex = '/youtu.be/([a-zA-Z0-9_-]+)??/i'; - Tim M
这应该是被接受的答案,它对我有很大帮助,谢谢! - Zach Tackett

43

试一下这个:

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

你能给一个输出的例子吗?请更新你的开头帖子 :) - Joran Den Houting
这是输出结果,请检查视频顶部的文字:http://img585.imageshack.us/img585/1025/vfxy.png - Hassan Sardar
这只是一个样式问题,与我的代码无关!您可以使用上述内容,只需调整文本的样式即可。 :) - Joran Den Houting
但是如果我按下回车键然后放置YouTube链接,样式完全没有问题,但对于单个链接,它会出现这种情况。 - Hassan Sardar
可能是因为 iframe 将出现在 <p> 标签内。如果是这样,您可以在结尾处添加一个闭合的 </p> - Joran Den Houting
显示剩余3条评论

33
Joran的解决方案稍作改进,以处理所有这些用例:
Long URL: https://www.youtube.com/watch?v=[ID]
    
Short URL: https://youtu.be/[ID]

Long URL with time parameter: https://www.youtube.com/watch?v=[ID]&t=[TIME]s

Short URL with time parameter: https://youtu.be/[ID]?t=[TIME]

Long URL with other parameters: https://www.youtube.com/watch?v=[ID]&t=[TIME]s&foo=hello&bar=world

Short URL with other parameters: https://youtu.be/[ID]?t=[TIME]&foo=hello&bar=world

Mobile URL: https://m.youtube.com/watch?v=[ID]&t=[TIME]s

function convertYoutube($string) {
    return preg_replace(
        "/[a-zA-Z\/\/:\.]*youtu(?:be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)(?:[&?\/]t=)?(\d*)(?:[a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i",
        "<iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/$1?start=$2\" allowfullscreen></iframe>",
        $string
    );
}

你可以在这里在线测试这个函数。


然而代码可以运行,但它只显示了一个小视频。 - John Max
3
你可以将 iframe 的宽度和高度设置为你想要的尺寸:http://syframework.alwaysdata.net/convert-youtube-url-to-iframe - Syone
这个不起作用。更改文本字符串中的任何内容并点击运行。iframe scr不再具有“v”值。 - pendingfox

16

快速生成FB / vimeo / youtube视频嵌入链接的函数。

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

9

例子:

$link1 = getEmbedUrl('https://www.youtube.com/watch?v=BIjqw7zuEVE');
$link2 = getEmbedUrl('https://vimeo.com/356810502');
$link3 = getEmbedUrl('https://example.com/link/12345');

功能:
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;
}

更新的Dailymotion链接:
$finalUrl .= 'https://geo.dailymotion.com/player.html?video='.$videoId;

嗨Suraj,我想知道如何使用它为每个视频生成缩略图?这可能吗? - Jay Smoke

3

我认为一种安全、超级简单的获得id的方法
而且比较无懈可击,就是使用URL结构。

function getYoutubeEmbedUrl($url){

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

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

3

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

它基本上是一个oembed库,可以将任何字符串中的YouTube网址转换为相应的iframe元素。我正在使用它,并将在各个地方继续使用它!


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> 

1
以下适用于所有类型的YouTube网址。
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);

$youtube_id = $match[1];

1

另一个简单的选择是使用parse_urlparse_str函数。

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

假设我们有以下两个链接:
$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

解释

parse_url 函数将链接分解为 4 个组成部分:schemehostpathquery (请参阅文档)

parse_url($link1);

// output
[
  "scheme" => "https",
  "host" => "www.youtube.com",
  "path" => "/watch",
  "query" => "v=NVcpJZJ60Ao",
]

$link2 的输出将是:

parse_url($link2);

// output
[
  "scheme" => "https",
  "host" => "www.youtu.be",
  "path" => "/NVcpJZJ60Ao",
]

parse_str函数将把查询字符串转换成数组(请参阅文档)

parse_str('v=NVcpJZJ60Ao', $output);

// value of variable $output
[
  "v" => "NVcpJZJ60Ao",
]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接