Search code examples
phpregexyoutubevimeo

PHP regex to match Vimeo text OR html link


I'm looking for a PHP regex that will scan a block of text and match any Vimeo URLs--either as plain text or in HTML links, so I can replace them with embedded videos.

I have a version of each working, but I'm not skilled enough to augment them so that it'll do both, and a lot of the half-working ones I've found don't seem to account for the wrinkles listed here: https://stackoverflow.com/a/12263701/1402052

The one that seems to effectively match HTML links:

$text = preg_replace('#(.*?)http://(www\.)?vimeo\.com/([^ ?\n/]+)((\?|/).*?(\n|\s))?.*#x', '<div class="video vimeo"><iframe src="//player.vimeo.com/video/$3" width="650" height="366" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>', $text);

The one that seems to effectively match plain text URLs:

$text = preg_replace('#http://(www\.)?vimeo\.com/(\d+)#', '<div class="video vimeo"><iframe src="//player.vimeo.com/video/$2" width="650" height="366" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>', $text);

These also seem to work if I run both (the former first), but I'm guessing there's a much better way.

Also, I say "seems to" because I haven't stressed tested either sufficiently yet. Any help is appreciated. :)


Solution

  • You can use Simple HTML DOM here:

    define( 
        'VIMEO_URL_PATTERN' ,
        '~https?://(?:www\.)?vimeo\.com/.*?/?(\d+)~i'
    );
    define(
        'URL_REPLACEMENT' ,
        '<div ... <iframe src="//player.vimeo.com/video/$1...</div>'
    );
    
    $html = ... // Load HTML code here
    
    // Change links
    foreach($html->find('a') as $link) {
        if (
           preg_match(
                VIMEO_URL_PATTERN,
                $link->href,
                $matches
           )
        ) {
            $link->outertext = preg_replace( 
                  VIMEO_URL_PATTERN,
                  URL_REPLACEMENT,
                  $link->href
            );
        }
    }
    
    // Change text
    foreach($html->find('text') as $text) {
        $text->outertext = preg_replace(
               VIMEO_URL_PATTERN,
               URL_REPLACEMENT,
               $text
        );
    }
    
    echo $html;