【问题标题】:Parse a message using php replacing youtube URL for youtube video ID [duplicate]使用php替换youtube视频ID的youtube URL解析消息[重复]
【发布时间】:2012-10-11 18:46:57
【问题描述】:

可能重复:
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

提前感谢:)

【问题讨论】:

  • 我不想只解析一个 URL 我想解析整条消息,这是一个 vBulletin 板,所以用户只粘贴一个链接,YouTube 视频就会神奇地出现 :)

标签: php regex parsing youtube preg-replace


【解决方案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

【讨论】:

  • “试试这个:”subpar answer decoration。相反,请添加对您的代码的什么为什么推荐它或如何得出结论的简要说明。 -- 更重要的是,如果您在其他地方找到了正则表达式,请注明出处。好像基于这个daringfireball.net/2009/11/liberal_regex_for_matching_urls
  • 那没用,如果有两个 url 的消息怎么办? :P 还是谢谢
  • 更新了多个 URL 示例。
  • 这将用于 vbulletin board,因此用户可以在他们的消息中输入 youtube 链接,然后 youtube 视频将自动出现,这是 CPU 密集型的吗?...谢谢!!!
猜你喜欢
  • 2011-12-14
  • 2011-02-25
  • 2015-09-20
  • 2012-01-25
  • 1970-01-01
  • 2011-11-05
  • 2011-11-19
  • 2011-08-25
  • 2011-10-12
相关资源
最近更新 更多