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


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

PHP 字符串中找到一个 Youtube 视频链接并将其转换为嵌入代码

嵌入代码:

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

PHP 代码/字符串:

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

优酷链接:

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

一个视频有两种类型的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 ;
}

$link 1 或 $link 2 的输出是相同的:

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

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

试试这个:

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的解决方案稍作增强,以处理所有这些用例:

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

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

一个快速函数,用于生成任何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;
}

示例:

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

更新了每日运动的链接:

$finalUrl .= 'https://geo.dailymotion.com/player.html?video='.$videoId;

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

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

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

function getYoutubeEmbedUrl($url){
    $urlParts   = explode('/', $url);
    $vidid      = explode( '&', str_replace('watch?v=', '', end($urlParts) ) );
    return 'https://www.youtube.com/embed/' . $vidid[0] ;
}

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

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> 

另一种简单的替代方法是使用 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",
]

好吧,您需要先过滤掉youtube链接并将它们放入数组中。接下来,您需要找出URL的视频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;
}

当然,您也可以使用PHP函数,但是我在这里只是使用JS从URL中获取id。也许这无论如何都有帮助;)

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

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

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

我主要使用ColdFsuion/Java,JSoup对于这种事情来说非常棒,也更加轻松和安全。

http://jsoup.org/

似乎,在PHP中,你可以使用这样的东西:

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

我很想给出一个代码示例,但我对PHP不够了解。但是放手一搏。

麦克。

也试试这个:

$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);
function convertYoutubeLinkToEmbed($text) {
    $pattern = '#https?://(?:www'.)?(?:youtube'.com/watch'?v=|youtu'.be/)(['w-]+)#i';
    $replacement = '<iframe width="560" height="315" src="https://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
    
    return preg_replace($pattern, $replacement, $text);
}

$text = 'Check this video: https://www.youtube.com/watch?v=0GfCP5CWHO0';
$embedText = convertYoutubeLinkToEmbed($text);
echo $embedText;