从 Youtube 中删除附加参数 link

Remove additional parameters from Youtube link

我有一个将 Youtube 链接转换为链接的 youtube 缩略图的功能。我还需要从 Youtube 链接中删除其他参数,例如:

https://www.youtube.com/watch?v=9_pIaI93YGY&list=RD9_pIaI93YGY&start_radio=1

需要:

https://www.youtube.com/watch?v=9_pIaI93YGY

这是我的代码:

$message = 'text text text https://www.youtube.com/watch?v=9_pIaI93YGY text text text https://www.youtube.com/watch?v=1PUT2a5NafI&list=RD1PUT2a5NafI&start_radio=1 more text more text';

$reg_exUrl_youtube = "/(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'> \r\n]+)(?![^<]*>)/";

$message = preg_replace_callback($reg_exUrl_youtube, function($matches) {
return "<div class=\"videoss videoss{$matches[1]}\"><a href=\"#\" class=\"videoshow\" id=\"{$matches[1]}\"><div style=\"background:url(/i/play.png) center no-repeat,url([zzzzz]img.youtube.com/vi/{$matches[1]}/mqdefault.jpg) center no-repeat;background-size:30%,cover;\" class=\"pd39 mroim60\"></div></a></div>";
}, $message);

但结果如下图所示。其他参数未被删除并显示为文本:

那么,如何从 Youtube 链接中删除所有附加参数?

使用您的模式,您可以使用 0+ 次非白色 space 字符 \S* 匹配捕获组之后的所有内容,这样它就不会出现在替换字符串中。

Regex demo | Php demo

该 ID 在组 1 中,您可以使用 $matches[1]

创建自定义替换

可以对您的模式进行一些优化。如果您使用不同于 / 的定界符,例如 ~,则不必转义正斜杠。

这些结构 (?:i)? 可以简化为 i? 并且您不必转义字符 class 中的 ?"。如果您不想匹配 space 或换行符,则在否定字符 class 中匹配 \s 可能会更短。

例如

$reg_exUrl_youtube = '~(?:https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com/(?:(?:watch)?\?(?:.*&)?vi?=|(?:embed|vi?|user)/))([^?&"\'>\s]+)(?![^<]*>)\S*~';
$message = 'text text text https://www.youtube.com/watch?v=9_pIaI93YGY text text text https://www.youtube.com/watch?v=1PUT2a5NafI&list=RD1PUT2a5NafI&start_radio=1 more text more text';

$message = preg_replace_callback($reg_exUrl_youtube, function($matches) {
    return "<div class=\"videoss videoss{$matches[1]}\"><a href=\"#\" class=\"videoshow\" id=\"{$matches[1]}\"><div style=\"background:url(/i/play.png) center no-repeat,url([zzzzz]img.youtube.com/vi/{$matches[1]}/mqdefault.jpg) center no-repeat;background-size:30%,cover;\" class=\"pd39 mroim60\"></div></a></div>";
}, $message);

echo $message;