正则表达式:在字符串中刷新YouTube网址,只保留YouTube视频代码

时间:2016-05-14 20:36:03

标签: php regex preg-replace preg-match

我的文字包含YouTube网址。我需要删除链接的所有部分,YouTube视频代码除外。 URL可能被空格包围或什么都没有;没有非空白字符将与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..."
)

2 个答案:

答案 0 :(得分:2)

如果我理解正确,以下内容适用于普通的YouTube链接(未经修改)。

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

替换为\1
(捕获第1组)

Regex demo.

答案 1 :(得分:1)

您可以尝试使用此模式进行匹配:

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

此表达式中只有一个捕获,它适用于YouTube视频代码。此捕获可与正则表达式替换一起使用,以仅使用捕获的视频代码替换整个链接文本。

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

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

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

此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, '$1', $txt);