正则表达式:擦除字符串中的 YouTube URL,只留下 YouTube 视频代码

Regex: Scrub a YouTube URL within a string, leaving only the YouTube video code

我有一个包含 YouTube URL 的文本。我需要删除 link 的所有部分,YouTube 视频代码除外。 URL 可能被空白包围 space 或什么都没有; URL.

旁边没有非空白字符

样本:

$txt = "This text contain this link: https://www.youtube.com/watch?v=b8ri14rw32c&rel=0 and so on..."

正在提取 ID:

$pattern = '#(?<=v=|v\/|vi=|vi\/|youtu.be\/)[a-zA-Z0-9_-]{11}#';
preg_match_all($pattern, $txt, $matches);
print_r($matches);

预期:

Array
(
    [0] = "This text contain this link b8ri14rw32c and so on..."
)

如果我没理解错的话,以下内容应该适用于正常的 YouTube 链接(未缩短)。

https?:\/\/[^\s]+[?&]v=([^&\s]+)[^\s]*

替换为
(捕获第 1 组)

Regex demo.

你可以试试这个模式来匹配:

https:\/\/(?:www.)?youtu(?:be\.com|\.be)\/(?:watch\?vi?[=\/])?(\w{11})(?:&\w+=[^&\s]*)*

这个表达式中只有一个捕获,它是针对 YouTube 视频代码的。此捕获可与正则表达式替换一起使用,以仅使用捕获的视频代码替换整个 link 文本。

此正则表达式适用于这些格式的 YouTube URLs:

https://www.youtube.com/watch?v=b8ri14rw32c&rel=0
https://youtu.be/Rk_sAHh9s08

其他 YouTube URL 格式尚未经过测试,但如果需要可以轻松支持。

此 PHP 代码将使用 preg_replace:

测试此正则表达式替换
$txt = "This text contain this link: https://www.youtube.com/watch?v=b8ri14rw32c&rel=0 and so on...";
$pattern = "/https:\/\/(?:www.)?youtu(?:be\.com|\.be)\/(?:watch\?vi?[=\/])?(\w{11})(?:&\w+=[^&\s]*)*/";
$text = preg_replace($pattern, '', $txt);