使用php解析消息,将youtube URL替换为youtube视频ID

使用php解析消息,将youtube URL替换为youtube视频ID,php,regex,parsing,youtube,preg-replace,Php,Regex,Parsing,Youtube,Preg Replace,可能重复: 上面的照片 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,然后从该URL提取一个有效的YouTube ID,如果找到一个有效的ID,则将找到的原始URL替换为匹配的ID: <?php

可能重复:

上面的照片

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,然后从该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;

来源:&

试试这个:是一个。相反,请添加一个简短的解释,说明您的代码是做什么的,为什么推荐它,或者您是如何得出结论的。-更重要的是,如果您在其他地方找到正则表达式,请注明归属。似乎基于这一点,如果有一条包含两个URL的消息,该怎么办P无论如何,感谢使用多URL示例更新。这将用于vbulletin板,因此用户可以在其消息上输入youtube链接,youtube视频将自动显示,这是CPU密集型吗?。。。谢谢我不想只解析一个URL,我想解析一条完整的消息,这是针对vBulletin板的,因此用户只需粘贴一个链接,youtube视频就会神奇地出现:
<?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;