0

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?

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

1 Answers1

2

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';
Pierre Michard
  • 1,341
  • 1
  • 12
  • 16
  • 1
    This is very nice, although it appears that there are even more variations of the YouTube URL. Can you kindly implement the regex provided here: http://stackoverflow.com/a/5831191/1185126 and add it with my regex in a way which it works? – Henrik Petterson Dec 24 '15 at 15:58