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?

1 Answer 1

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';
Sign up to request clarification or add additional context in comments.

1 Comment

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: stackoverflow.com/a/5831191/1185126 and add it with my regex in a way which it works?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.