regex - 使用正则表达式获取存储在字符串中的YouTube URL

标签 regex url youtube

我有一个使用正则表达式并返回YouTube URL数组的函数。

function getYoutubeUrlsFromString($string) {
    $regex = '#(https?:\/\/(?:www\.)?(?:youtube.com\/watch\?v=|youtu.be\/)([a-zA-Z0-9]*))#i';
    preg_match_all($regex, $string, $matches);
    $matches = array_unique($matches[0]);           
    usort($matches, function($a, $b) {
        return strlen($b) - strlen($a);
    });
    return $matches;
}

例:
$html = '<p>hello<a href="https://www.youtube.com/watch?v=7HknMcG2qYo">world</a></p><p>hello<a href="https://youtube.com/watch?v=37373o">world</a></p>';
$urls = getYoutubeUrlsFromString($html);

可以很好地用于以下网址:
https://www.youtube.com/watch?v=KZhJT3COzPc

但不适用于以下网址:
https://www.youtube.com/embed/VBp7zW9hxZY

如何更改正则表达式,使其获得这种类型的YouTube URL?

最佳答案

这应该同时允许watch?v=embed/

'#(https?:\/\/(?:www\.)?(?:youtube.com\/(?:watch\?v=|embed\/)|youtu.be\/)([a-zA-Z0-9]*))#i';

请注意,您还应该转义.com或.be的点,否则它将接受任何字符:
'#(https?:\/\/(?:www\.)?(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9]*))#i';

关于regex - 使用正则表达式获取存储在字符串中的YouTube URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34454935/

相关文章:

javascript - 正则表达式不起作用

javascript - http ://. 的正则表达式 .. 在 <a> 之外

json - Phabricator linter 找不到任何 lintable 路径

apache - 如何为 JSP 和 SEO 友好的干净 URL 设置 Apache 和 Tomcat

android - Share Intent 不适用于将视频上传到 youtube

html - 正则表达式抓取表单标签内容不起作用

python urllib.parse.urljoin 在以数字和冒号开头的路径上

python - 如何重定向到另一个应用程序中的 View 并仍然传递参数(Django)

javascript - 视频 js 给出错误代码 :150 undefined

python - 使用Python分析YouTube评论-参数已禁用评论