2011-11-19 46 views
6

如果在字符串中找到了此函数,该函数会嵌入youtube视频。用HTML嵌入代码替换文本中的YouTube网址

我的问题是什么是最简单的方法来捕获嵌入式视频(iframe和只有第一个,如果有更多的),并忽略其余的字符串。

function youtube($string,$autoplay=0,$width=480,$height=390) 
{ 
preg_match('#(v\/|watch\?v=)([\w\-]+)#', $string, $match); 
    return preg_replace(
    '#((http://)?(www.)?youtube\.com/watch\?[=a-z0-9&_;-]+)#i', 
    "<div align=\"center\"><iframe title=\"YouTube video player\" width=\"$width\" height=\"$height\" src=\"http://www.youtube.com/embed/$match[2]?autoplay=$autoplay\" frameborder=\"0\" allowfullscreen></iframe></div>", 
    $string); 
} 
+0

最简单,最稳健的方法是不使用正则表达式。 – FailedDev

+0

@FailedDev小心告诉我如何(不一定是相同的功能)? – domino

+0

您正在将$ string的部分传递给$ string吗?你怎么得到这个字符串? – FailedDev

回答

13

好吧,我想我明白你想要完成什么。用户输入一段文字(某些评论或任何内容),并在该文本中找到一个YouTube网址,并将其替换为实际的视频嵌入代码。

以下是我已经修改了它:

function youtube($string,$autoplay=0,$width=480,$height=390) 
{ 
    preg_match('#(?:http://)?(?:www\.)?(?:youtube\.com/(?:v/|watch\?v=)|youtu\.be/)([\w-]+)(?:\S+)?#', $string, $match); 
    $embed = <<<YOUTUBE 
     <div align="center"> 
      <iframe title="YouTube video player" width="$width" height="$height" src="http://www.youtube.com/embed/$match[1]?autoplay=$autoplay" frameborder="0" allowfullscreen></iframe> 
     </div> 
YOUTUBE; 

    return str_replace($match[0], $embed, $string); 
} 

既然你已经定位与第一preg_match()的URL,就没有必要运行另一个正则表达式函数替换它。让它匹配整个网址,然后在整个比赛中做一个简单的str_replace()$match[0])。视频代码在第一个子模式中被捕获($match[1])。我正在使用preg_match(),因为您只想匹配找到的第一个网址。如果您想匹配所有网址,则必须使用preg_match_all()并修改代码,而不仅仅是第一个。

这里是我的正则表达式的解释:

(?:http://)? # optional protocol, non-capturing 
(?:www\.)?  # optional "www.", non-capturing 
(?: 
       # either "youtube.com/v/XXX" or "youtube.com/watch?v=XXX" 
    youtube\.com/(?:v/|watch\?v=) 
    | 
    youtu\.be/  # or a "youtu.be" shortener URL 
) 
([\w-]+)  # the video code 
(?:\S+)?  # optional non-whitespace characters (other URL params) 
+0

我一直在网上搜索这个脚本。这个工作,但它只检测内容中的第一个网址。例如,我在内容中有3个youtube网址。第一个视频会嵌入,而其他视频只显示链接。 我该怎么办? – Wilf

+0

我懂了!只需将'preg_match'改为'preg_match_all' ...感谢数百万人! – Wilf

+0

我有这个工作:http://stackoverflow.com/a/5452862/1620626 – Wilf

相关问题