Skip to content

Instantly share code, notes, and snippets.

@braginteractive
Last active April 11, 2017 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save braginteractive/9861637a3b536b6776a2b93cccbb9e33 to your computer and use it in GitHub Desktop.
Save braginteractive/9861637a3b536b6776a2b93cccbb9e33 to your computer and use it in GitHub Desktop.
Get YouTube video ID from URL
<?php
/**
* Get the ID of a YouTube Video
**/
function helpwp_youtube_id($url){
/*
* type1: http://www.youtube.com/watch?v=9Jr6OtgiOIw
* type2: http://www.youtube.com/watch?v=9Jr6OtgiOIw&feature=related
* type3: http://youtu.be/9Jr6OtgiOIw
*/
$vid_id = "";
$flag = false;
if(isset($url) && !empty($url)){
/*case1 and 2*/
$parts = explode("?", $url);
if(isset($parts) && !empty($parts) && is_array($parts) && count($parts)>1){
$params = explode("&", $parts[1]);
if(isset($params) && !empty($params) && is_array($params)){
foreach($params as $param){
$kv = explode("=", $param);
if(isset($kv) && !empty($kv) && is_array($kv) && count($kv)>1){
if($kv[0]=='v'){
$vid_id = $kv[1];
$flag = true;
break;
}
}
}
}
}
/*case 3*/
if(!$flag){
$needle = "youtu.be/";
$pos = null;
$pos = strpos($url, $needle);
if ($pos !== false) {
$start = $pos + strlen($needle);
$vid_id = substr($url, $start, 11);
$flag = true;
}
}
}
return $vid_id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment