【问题标题】:Find youtube Link in PHP string and Convert it into embed code?在 PHP 字符串中查找 youtube 链接并将其转换为嵌入代码?
【发布时间】:2013-10-03 18:12:27
【问题描述】:

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

【问题讨论】:

标签: php string replace youtube find


【解决方案1】:

试试这个:

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

【讨论】:

  • 其余代码运行良好,但如果我发布:“查看此视频:youtube.com/watch?v=0GfCP5CWHO0”。视频确实出现了,但文本出现的空格太多
  • 你能举一个输出的例子吗?请更新您的职位空缺:)
  • 这里是输出,请查看视频顶部的文字:img585.imageshack.us/img585/1025/vfxy.png
  • 这是一个样式问题,与我的代码无关!您可以使用上述内容,只需要设置文本样式。 :)
  • 但是没有这个代码的样式是完全完美的,如果我按下回车键然后放置 youtube 链接,它工作正常,但是对于单个链接,它出现链接这个
【解决方案2】:

一个视频有两种类型的 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&amp;v=NVcpJZJ60Ao
  • 我为此添加了一个连字符以使其与我的一些共享链接一起使用:$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_-]+)\? ?/i';
  • 这应该是公认的答案,对我帮助很大,谢谢!
【解决方案3】:

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

你可以在线测试这个功能here

【讨论】:

【解决方案4】:

用于生成任何 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;
}

【讨论】:

    【解决方案5】:

    例子:

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

    【讨论】:

    • 嗨 Suraj,我想知道如何使用它为每个视频生成缩略图?这可能吗?
    【解决方案6】:

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

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

    【讨论】:

      【解决方案7】:

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

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

      【讨论】:

        【解决方案8】:

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

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

        【讨论】:

          【解决方案9】:
          <?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> 
          

          【讨论】:

            【解决方案10】:

            好吧,您需要先过滤掉 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,您可以嵌入视频;)

            【讨论】:

              【解决方案11】:

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

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

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

              http://jsoup.org/

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

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

              我很想提供一个代码示例,但我对 PHP 的了解不够。不过试试看吧。

              米奇。

              【讨论】:

              • $purifier-&gt;purify(preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&amp;\;\%\=\.]*)/i","&lt;iframe width=\"315\" height=\"210\" src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen&gt;&lt;/iframe&gt;",$chat_info['text'])); 就足够了吗?
              【解决方案12】:

              另一个简单的替代方法是使用 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(see docs)

              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 会将查询字符串转换为数组(see docs)

              parse_str('v=NVcpJZJ60Ao', $output);
              
              // value of variable $output
              [
                "v" => "NVcpJZJ60Ao",
              ]
              

              【讨论】:

                【解决方案13】:

                也试试这个:

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

                【讨论】:

                  猜你喜欢
                  • 2015-02-12
                  • 1970-01-01
                  • 1970-01-01
                  • 2013-03-27
                  • 1970-01-01
                  • 1970-01-01
                  • 2012-08-03
                  • 2015-03-02
                  • 1970-01-01
                  相关资源
                  最近更新 更多