Skip to content

Instantly share code, notes, and snippets.

@mchamplain
Created February 20, 2014 01:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mchamplain/9105581 to your computer and use it in GitHub Desktop.
Save mchamplain/9105581 to your computer and use it in GitHub Desktop.
Regex to parse a youtube URL and extract the video id
<?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