【问题标题】:Grab YouTube URL stored in string using regex使用正则表达式获取存储在字符串中的 YouTube URL
【发布时间】:2015-12-24 15:32:40
【问题描述】:

我有一个函数,它使用正则表达式并返回一组 YouTube 网址。

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 网址?

【问题讨论】:

    标签: regex url youtube


    【解决方案1】:

    这应该允许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';
    

    【讨论】:

    • 这非常好,尽管 YouTube URL 似乎还有更多变体。您能否实现此处提供的正则表达式:stackoverflow.com/a/5831191/1185126 并以可行的方式将其添加到我的正则表达式中?
    猜你喜欢
    • 2016-04-05
    • 2011-05-31
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 2015-10-30
    • 2017-05-30
    • 1970-01-01
    • 2019-05-02
    相关资源
    最近更新 更多