2012-10-21 50 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感谢 –