Skip to content

Instantly share code, notes, and snippets.

@macu
Last active March 25, 2020 19:24
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 macu/43b1232cc173c42f03a3aed0d2c47f34 to your computer and use it in GitHub Desktop.
Save macu/43b1232cc173c42f03a3aed0d2c47f34 to your computer and use it in GitHub Desktop.
Extract video IDs from YouTube and Vimeo embed codes
YouTube embed regex:
/<iframe\s+[^>]*?src="(?:(?:https?:)?\/\/)?(?:(?:www|m)\.)?(?:youtube\.com|youtu.be)(?:\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)[^">]*?"[^>]*>[^<]*<\/iframe>/
Vimeo embed regex:
/<iframe\s+[^>]*?src="(?:(?:https?:)?\/\/)?(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/[^\/]+\/videos\/|album\/\d+\/video\/|video\/|)(\d+)\/?(?:[?]?[^">]*)"[^>]*>[^<]*<\/iframe>/
<?php
function getVimeoImageUrl($videoId) {
$ch = curl_init("http://vimeo.com/api/v2/video/" . $videoId . ".json");
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')){
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
$json = json_decode($response, true);
return $json[0]["thumbnail_large"];
}
return null;
}
function getYoutubeImageUrl($videoId) {
return "https://i1.ytimg.com/vi/$videoId/hqdefault.jpg";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment