2012-04-25 58 views
0

好大家好,我发现这样做的多种方式,我甚至已完成了工作,但我的问题是这样的,从我了解的preg_replace应该替换的模式相匹配的一切,但它似乎只能运行一次。PHP的preg_replace Youtube链接到嵌入链接

这是我需要的,我有一个网站正在运行一项功能,让用户在他们的个人资料上张贴他们想要的任何内容,我们希望让他们发布youtube链接并将这些链接变为嵌入。问题出现在他们发布多个视频时,它只会嵌入其中一个视频,更糟糕的是会删除文字。

$test = "This is a great lecture: http://www.youtube.com/watch?v=Ps8jOj7diA0 This is another great lecture http://www.youtube.com/watch?v=k6U-i4gXkLM What are your opinions on the two?" 
$patterns[] = '|http://www\.youtube\.com/watch\?.*\bv=([^ ]+)|'; 
$replacements[] = ' <br /><iframe width="420" height="315" src=http://www.youtube.com/embed/$1 frameborder="0" allowfullscreen></iframe><br />'; 
$patterns[] = '|&feature=related|'; 
$replacements[] = ''; 
$test = preg_replace($patterns, $replacements, $test); 
echo $test; 
Output: 
"This is a great lecture: 
<iframe width="420" height="315" src=http://www.youtube.com/embed/k6U-i4gXkLM frameborder="0" allowfullscreen></iframe> 
What are your opinions on the two?" 

所以,你看到...它切断了第一个和第二个视频之间的所有内容,只嵌入第二个视频。我需要一个解决方案,可以让我删除由YouTube链接产生的额外内容,并保留用户发布的所有消息文本。任何想法的家伙?谢谢。

+1

你真的不应该使用'|'作为你的正则表达式分隔符。几乎每个人都希望它在正则表达式中具有“或”的通用含义。 – ThiefMaster 2012-04-25 21:47:20

回答

2

使其成为非贪婪。

http://www\.youtube\.com/watch\?.*?\bv=([^ ]+) 

注意额外?这里?.*?http://www\.youtube\.com/watch\?.*\bv=([^ ]+)

+0

它就像现货的区别:P – Lix 2012-04-25 21:47:52

+0

您先生,真棒:D非常感谢<3 – 2012-04-25 21:52:57

0

有两个问题与杰克代码: - 它不能正常赶上在一行的末尾链接(\ n字符) - 它不会删除可选的附加参数(例如&列表= ...。)

下面是完整的代码:

$test = "This is a great lecture: http://www.youtube.com/watch?v=Ps8jOj7diA0&list=PL33AFE53E080251DF This is another great lecture http://www.youtube.com/watch?v=k6U-i4gXkLM What are your opinions on the two?" 
$patterns = array('|http://www\.youtube\.com/watch\?.*?\bv=([^&]+).+?\s|i'); 
$replacements = array(' <br /><iframe width="400" height="300" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe><br />'); 
$test= preg_replace($patterns, $replacements, $test);