$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 :(得分:1)
首先,您要匹配有效的网址,然后从该网址中提取有效的YouTube ID,然后将找到的原始网址替换为匹配的ID(如果找到了有效的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&amp; https://stackoverflow.com/a/6382259/1748964