2011-11-19 190 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