2012-10-21 102 views
-3

可能重複:
parse youtube video id using preg_match解析的消息

$message = "this is an youtube video http://www.youtube.com/watch?v=w6yF_UV1n1o&feature=fvst i want only the id"; 

$message = preg_replace('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', '\\1', $message); 

print $message; 

上面印...

this is an youtube video http://www.w6yF_UV1n1o&feature=fvst i want only the id 

什麼我想要的是:

this is an youtube video w6yF_UV1n1o i want only the id 

在此先感謝:)

+0

我並不想只分析一個URL我想解析整個消息,這是一個vBulletin蟒蛇第三,讓用戶CA只粘貼鏈接和YouTube視頻會奇蹟般地出現:) –

回答

1

首先,你將匹配一個有效的URL,然後從URL中提取有效的YouTube ID,然後更換相匹配的ID找到原始URL(如果一個有效的ID是發現):

<?php 

$message = " 
    this is a youtube video http://www.youtube.com/watch?v=w6yF_UV1n1o&feature=fvst i want only the id 
    this is not a youtube video http://google.com do nothing 
    this is an youtube video http://www.youtube.com/watch?v=w6yF_UV1n1o&feature=fvst i want only the id 
"; 

preg_match_all('#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#', $message, $matches); 

if (isset($matches[0])) 
{ 
    foreach ($matches[0] AS $url) 
    { 
     if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $matches)) 
      $message = str_replace($url, $matches[1], $message); 
    } 
} 

echo $message; 

來源:http://daringfireball.net/2009/11/liberal_regex_for_matching_urls & https://stackoverflow.com/a/6382259/1748964

+0

*「試試這個:」 *是[欠佳答案裝飾](http://stuck.include-once.org/#help10) 。相反,請給你的代碼做些什麼,爲什麼要推薦它,或者你如何得出結論。 - 更重要的是,如果你在其他地方找到了正則表達式,請註明歸屬地。似乎在此基礎上一個http://daringfireball.net/2009/11/liberal_regex_for_matching_urls – mario

+0

尼斯!謝謝<3 –

+0

那麼沒有工作,如果有兩個網站的消息呢? :P感謝 –