正则表达式替换iftube视频ID的iframe / object

时间:2014-03-21 07:07:14

标签: php regex

我有如下的html。基本上它有三个视频,其中一些嵌入iframe标记其他对象标记。我有YouTube视频ID。所以我想用YouTube视频ID替换iframe / object标记中的一些文本(视频无法在此处显示)。

我的HTML

<p>Video 1</p>
<p><iframe width="604" height="453" src="http://www.youtube.com/embed/TOsGAxFcYls?feature=oembed" frameborder="0" allowfullscreen></iframe></p>

<p>Video 2</p>
<p><iframe width="604" height="340" src="http://www.youtube.com/embed/Y-AYC3_DbpY?feature=oembed" frameborder="0" allowfullscreen></iframe></p>


<p>Video 3</p>

<object width="560" height="315"><param name="movie" value="//www.youtube.com/v/-1jKtYuXkrQ?version=3&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="//www.youtube.com/v/-1jKtYuXkrQ?version=3&hl=en_US" type="application/x-shockwave-flash" width="560" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>

现在,我想替换替换视频1和3.我有两个视频ID。

  • 视频1 = TOsGAxFcYls
  • 视频3 = -1jKtYuXkrQ

现在,我想用特定文本替换iframe和object。

预期输出

    <p>Video 1</p>
    <p><strong>Video 1 has been removed video id (TOsGAxFcYls)</strong></p>

    <p>Video 2</p>
    <p><iframe width="604" height="340" src="http://www.youtube.com/embed/Y-AYC3_DbpY?feature=oembed" frameborder="0" allowfullscreen></iframe></p>


    <p>Video 3</p>

   <strong>Video 3 has been removed video id (-1jKtYuXkrQ)</strong>
  

注意:我可以为每次替换添加自定义替换文本   视频。

请帮我正则表达做上述工作!

2 个答案:

答案 0 :(得分:1)

这是一个简单的解决方案,只需将ID及其替换文本添加到$video_ids数组中。

$html= ... // your html here
$video_ids = array
    (
      array("TOsGAxFcYls","First replacement text"),
      array("Y-AYC3_DbpY","Second replacement text")
    );    

foreach ($video_ids as &$video_id) {
    $patt = "/<object(.*)$video_id[0](.*)<\/object>/";
    $html = preg_replace($patt, $video_id[1], $html);
    $patt = "/<iframe.*?src\=".*?'.$video_id[0].'.*.<\/iframe>/i";
    $html = preg_replace($patt, $video_id[1], $html);
}

echo $html; // here are your changed values

答案 1 :(得分:1)

以下是我认为会产生影响的示例代码:

<?php
$text = '<iframe width="604" height="340" src="http://www.youtube.com/embed/Y-AYC3_DbpY?feature=oembed" frameborder="0" allowfullscreen></iframe>';

$matches = array();
$video_id = "Y-AYC3_DbpY";
preg_match('/<iframe.*?src\=".*?'.$video_id.'.*.<\/iframe>/i', $text, $matches);
if(!empty($matches)){
    //replace iframe;
}
else{
    //do something else
}
?>