Created
February 20, 2014 01:56
-
-
Save mchamplain/9105581 to your computer and use it in GitHub Desktop.
Regex to parse a youtube URL and extract the video id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public static function getYoutubeVideoIdFromUrl($url) | |
{ | |
// Check for a valid youtube url | |
$rx = '~ # Using ~ to avoid LTS (http://en.wikipedia.org/wiki/Leaning_toothpick_syndrome) | |
^http(?:s)?:// # Mandatory protocol (optional ssl) | |
(?:www\.)? # Optional subdomain | |
(?:youtube\.com/watch(?:/)?\?v=|youtu\.be/) # mandatory domain & path for youtube or shortlink for youtu.be | |
([^?&]+) # video id as capture group 1 | |
~x'; | |
$has_match = preg_match($rx, $url, $matches); | |
if ($has_match) | |
{ | |
return $matches[1]; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment