【问题标题】:PHP extract youtube video IDs from array of iframe/object embeds?PHP 从 iframe/对象嵌入数组中提取 youtube 视频 ID?
【发布时间】:2012-01-04 21:09:59
【问题描述】:

我有一个这样的 youtube iframe/对象数组:

[0] => <iframe width="600" height="338" src="http://www.youtube.com/embed/szL_PVuzWp0?fs=1&feature=oembed" frameborder="0" allowfullscreen></iframe>
[1] => <object width="600" height="338"><param name="movie" value="http://www.youtube.com/v/jm1S43a-e3Y?version=3&feature=oembed"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/jm1S43a-e3Y?version=3&feature=oembed" type="application/x-shockwave-flash" width="600" height="338" allowscriptaccess="always" allowfullscreen="true"></embed></object>
[2] => <iframe width="600" height="338" src="http://www.youtube.com/embed/7fTploFSbXA?fs=1&feature=oembed" frameborder="0" allowfullscreen></iframe>
[3] => <iframe width="600" height="338" src="http://www.youtube.com/embed/vQSRNYgiuMk?fs=1&feature=oembed" frameborder="0" allowfullscreen></iframe>

请注意,嵌入方法可能会有所不同(通常&lt;iframe&gt;,偶尔&lt;object&gt;)(由于外部数据源)。

我将如何/最可靠的方法来提取每个视频 URL(例如 vQSRNYgiuMk 或 jm1S43a-e3Y)?

最终我想得到一个像这样的数组:

[0] => "szL_PVuzWp0"
[1] => "jm1S43a-e3Y"
[2] => "7fTploFSbXA"
[3] => "vQSRNYgiuMk"

【问题讨论】:

标签: php regex dom youtube


【解决方案1】:

请不要使用正则表达式:

   $dom_document = new DOMDocument();

   $dom_document->loadHTML($html);

   //use DOMXpath to navigate the html with the DOM
   $dom_xpath = new DOMXpath($dom_document);

   // if you want to get the all the iframes
   $iframes = $dom_xpath->query("//iframe");

   if (!is_null($iframes)) {
      foreach ($iframes as $iframe) {
        if($iframe->hasAttributes()){ 
            $attributes = $iframe->attributes; 
            if(!is_null($attributes)){ 
               foreach ($attributes as $index=>$attr){ 
                  if($attr->name == 'src'){ 
                     $curSrc = $attr->value; 
                     //use regex here to extract what you want
                  } 
               } 
            } 
         } 
      }
   }

不是完整的解决方案。但是你明白了……

【讨论】:

  • 有必要使用DOM吗?这是访问 src 字符串的最简单方法吗?
  • @samb 您正在有效地尝试使用正则表达式解析 html。虽然可以做到,但最终结果将是一个不太好的解析器。使用 DOM,您不会出错。如果您的 html 结构发生了某些变化,那么如果您使用的是简单的正则表达式,那么您注定要失败。
  • 完全同意这个方案。 DOM 方法总是更好。感谢您的解决方案。
  • 这是我书中的答案。工作完美。谢谢!
【解决方案2】:
foreach($arr as $i=>$a){
    $start = strpos($a, "/v/") + 3;
    if(!$start) $start = strpos($a, "/embed/") + 7;
    $qm = strpos("?");
    $length = $qm - $start;
    $new_array[$i] = substr($a, $start, $length);
}

【讨论】:

  • 关闭但导致例如'/v/jm1S43a-' 或 '/embed/szL_'(包括 11 个字符中的前缀)
  • 另外,IIRC youtube url 的长度可以是 10-12 个字符。
  • 这是一个不错的解决方案,非常感谢。但在更广泛的背景下,更好的解决方案是直接访问 URL(在外部 API 中添加一个参数),而不是在 HTML 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
  • 2011-11-19
  • 2014-05-26
  • 2016-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多