2012-04-25 81 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);