Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
YouTube URL PHP Regexp Shit
<?php
/**
* YouTube Preg Match Test Case.
*
* @author Mario "Kuroir" Ricalde
*/
// Regular Expression (the magic).
$youtube_regexp = "/^http:\/\/(?:www\.)?(?:youtube.com|youtu.be)\/(?:watch\?(?=.*v=([\w\-]+))(?:\S+)?|([\w\-]+))$/";
// The test urls, one per line.
$urls = <<<EOF
http://www.youtube.com/watch?v=4-iI6UnKUCs&feature=grec_index
http://www.youtube.com/watch?v=4-iI6UnKUCs
http://www.youtube.com/watch?v=QNnz_ktVggQ&NR=1
http://youtu.be/QNnz_ktVAA
http://youtu.x
EOF;
// Turn each line into one single element in an array.
$urls = explode("\n", $urls);
foreach ($urls as $url) {
// Match a URL.
preg_match($youtube_regexp, $url, $matches);
// Remove empty values from the array (regexp shit).
$matches = array_filter($matches, function($var) {
return($var !== '');
});
// If we have 2 elements in array, it means we got a valid url!
// $matches[2] is the youtube ID!
if (sizeof($matches) == 2) {
var_dump($matches);
}
}
@clemorphy

This comment has been minimized.

Copy link

clemorphy commented Nov 10, 2015

It considers http://www.youtube.com/watch is a valid URL, but it's not

@deathsoul00

This comment has been minimized.

Copy link

deathsoul00 commented Jun 2, 2016

try this one instead. works fine in this some urls

https://youtube.com/watch?v={video_id}&param1={value}
https://youtube.com/watch?v={video_id}

$pattern = '%^(?:https?://)?(?:www.)?(?:youtu.be/|youtube.com(?:/embed/|/v/|/watch?v=))([\w-]{10,12})(?:\S+)$%x';

@loter

This comment has been minimized.

Copy link

loter commented Jul 15, 2016

%^(?:https?://)?(?:www.)?(?:youtu.be/|youtube.com(?:/embed/|/v/|/watch?v=))([\w-]{10,12})(?:\S+)$%x will not validate
http://www.youtube.com/watch?v=8F5VSKT38r0
correctly.
MATCH 1

  1. [31-41] 8F5VSKT38r
    QUICK REFERENCE
@tiagopedrogomes

This comment has been minimized.

Copy link

tiagopedrogomes commented Oct 26, 2016

I add "https://" for the start of string

/^(http://|https://)(?:www.)?(?:youtube.com|youtu.be)/(?:watch?(?=.*v=([\w-]+))(?:\S+)?|([\w-]+))$/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.