0

I've been working on a Youtube and Vimeo embed code parser, I'm trying to solve problem by using regular expressions.

I've found two patterns and they're working with eregi() function but unfortunately doesn't work with preg_match(). Gives "Delimiter must not be alphanumeric or backslash" error.

How can I convert these patterns from POSIX to PCRE?

For Youtube;

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

For Vimeo;

player\.vimeo\.com\/video/([0-9]*)"
she hates me
  • 1,212
  • 5
  • 25
  • 44

2 Answers2

0

I found this one helpful in a site I help develop. Thanks and credit go to 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,
          | </a>          # or inside <a> element text contents.
          )               # End recognized pre-linked alts.
        )                 # End negative lookahead assertion.
        [?=&+%\w-]*        # Consume any URL (query) remainder.
        ~ix', 
        '<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>',
        $text);
    return $text;
}

You should be able to strip what you need out of there, and it handles all styles of YouTube links. Vimeo shouldn't be too hard from there.

Community
  • 1
  • 1
Chris Doggett
  • 19,959
  • 4
  • 61
  • 86
0

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

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

When using PCRE, make sure, you enclose the expression in /expression/ (slashes), and escape also all the /. I noticed you do sometimes, sometimes you don't ...

jadkik94
  • 7,000
  • 2
  • 30
  • 39