-3

可能重复:
使用 preg_match 解析 youtube 视频 ID

$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

提前致谢 :)

4

1 回答 1

1

首先,您将匹配一个有效的 URL,然后从该 URL 中提取一个有效的 YouTube ID,然后将找到的原始 URL 替换为匹配的 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 & https://stackoverflow.com/a/6382259/1748964

于 2012-10-21T23:45:51.543 回答