Henrik Petterson
Henrik Petterson

Reputation: 7094

Grab YouTube URL stored in string using regex

I have a funciton which uses regex and returns an array of YouTube urls.

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;
}

Example:

$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);

This works fine with URLs like:

https://www.youtube.com/watch?v=KZhJT3COzPc

But it doesn't work with URLs like:

https://www.youtube.com/embed/VBp7zW9hxZY

How can I change the regex so it gets this type of YouTube URL?

Upvotes: 0

Views: 51

Answers (1)

Pierre Michard
Pierre Michard

Reputation: 1391

This should allow both watch?v= and embed/

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

Note that you should also escape the points for .com or .be, otherwise it accepts any character:

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

Upvotes: 2

Related Questions