使用PCRE Regex的YouTube和Vimeo嵌入代码解析器

我一直在研究Youtube和Vimeo嵌入代码解析器,我试图通过使用正则表达式来解决问题。

我发现了两种模式,他们正在使用eregi()函数,但不幸的是,它不适用于preg_match()。给出“分隔符不能是字母数字或反斜杠”错误。

我怎样才能将这些模式从POSIX转换为PCRE?

对于Youtube;

\/v\/(.{11})|\/embed\/(.{11})

对于Vimeo;

player\.vimeo\.com\/video/([0-9]*)"
0
额外 编辑
意见: 1
最后的双引号是复制粘贴错误吗?
额外 作者 jadkik94,

2 答案

我发现这一个有帮助我帮助发展的网站。感谢和信任去 ridgerunner

// Linkify youtube URLs which are not already links.
function linkifyYouTubeURLs($text) {
    $text = preg_replace('~
        # Match non-linked youtube URL in the wild. (Rev:20111012)
        https?://         # Required scheme. Either http or https.
        (?:[0-9A-Z-]+\.)? # Optional subdomain.
        (?:               # Group host alternatives.
          youtu\.be/      # Either youtu.be,
        | youtube\.com    # or youtube.com followed by
          \S*             # Allow anything up to VIDEO_ID,
          [^\w\-\s]       # but char before ID is non-ID char.
        )                 # End host alternatives.
        ([\w\-]{11})      # $1: VIDEO_ID is exactly 11 chars.
        (?=[^\w\-]|$)     # Assert next char is non-ID or EOS.
        (?!               # Assert URL is not pre-linked.
          [?=&+%\w]*      # Allow URL (query) remainder.
          (?:             # Group pre-linked alternatives.
            [\'"][^<>]*>  # Either inside a start tag,
          |           # or inside  element text contents.
          )               # End recognized pre-linked alts.
        )                 # End negative lookahead assertion.
        [?=&+%\w-]*        # Consume any URL (query) remainder.
        ~ix', 
        'YouTube link: $1',
        $text);
    return $text;
}

你应该能够去掉你需要的东西,并且它可以处理所有YouTube链接的风格。 Vimeo从那里不应该太难。

0
额外

This is for youtube:$pattern = '/\/v\/(.{11})|\/embed\/(.{11})/';

And that's for Vimeo: $pattern = '/player\.vimeo\.com\/video\/([0-9]*)/';

使用PCRE时,请确保将表达式放在/expression/(斜杠)中,并且还要转义所有/。我注意到你有时会做,有时候你不会......

0
额外