如何在PHP中执行此REGEX?

时间:2011-11-02 15:56:29

标签: php regex

我有一个youtube视频嵌入代码,如下所示:

<iframe width="560" height="315" src="http://www.youtube.com/embed/XGdfNb15h9o" frameborder="0" allowfullscreen></iframe>

我需要添加以下内容(它摆脱了相关的视频建议):

?rel=0

到嵌入代码中每个网址的末尾。因此,在上面的示例中,最终代码应如下所示:

<iframe width="560" height="315" src="http://www.youtube.com/embed/XGdfNb15h9o?rel=0" frameborder="0" allowfullscreen></iframe>

嵌入代码存储在名为$embed_code的变量中。如何将嵌入代码转换为适用于它的?rel=0

5 个答案:

答案 0 :(得分:2)

如果其他一切都保持不变,你可以使用str_replace,这样会更快。

    <?php
$iframe = '<iframe width="560" height="315" src="http://www.youtube.com/embed/XGdfNb15h9o" frameborder="0" allowfullscreen></iframe>';
$pattern = '" frameborder="0"';
$replace = '?rel=0" frameborder="0"';

$iframe = str_replace($pattern,$replace, $iframe);

echo $iframe;

?>

答案 1 :(得分:1)

如果没有更多信息或源代码,我认为您不需要正则表达式。为什么不这样做:

$embed_code.= "?rel=0";
输出HTML之前

答案 2 :(得分:1)

这就是你想要的: preg_replace('~src=('|")(http://www.youtube\.com.+?)\1~',"src='\2?rel=0'",$input);

答案 3 :(得分:1)

又一个不同的答案:

$result = preg_replace('/(src\s*=([\'"]).*?(?=\2))/s', '$1?rel=0', $subject);

我猜上述正则表达式中的任何一个都可行。这只是一个偏好问题:)

说明:

"
(             # Match the regular expression below and capture its match into backreference number 1
   src           # Match the characters “src” literally
   \s            # Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
      *             # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   =             # Match the character “=” literally
   (             # Match the regular expression below and capture its match into backreference number 2
      ['\"]          # Match a single character present in the list “'\"”
   )
   .             # Match any single character
      *?            # Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
   (?=           # Assert that the regex below can be matched, starting at this position (positive lookahead)
      \2            # Match the same text as most recently matched by capturing group number 2
   )
)
"

答案 4 :(得分:0)

这样的事情应该这样做。

$str = '<iframe width="560" height="315" src="http://www.youtube.com/embed/XGdfNb15h9o" frameborder="0" allowfullscreen></iframe>';
$pattern = '/(http:\/\/www.youtube.com[^\"]*)/';
$str = preg_replace($pattern,"$1?rel=0",$str);
echo $str;