Skip to content

Instantly share code, notes, and snippets.

@nagiyevelchin
Last active October 7, 2023 11:28
Show Gist options
  • Save nagiyevelchin/84d0a8661f3a7c7d7945f702e8f05ce0 to your computer and use it in GitHub Desktop.
Save nagiyevelchin/84d0a8661f3a7c7d7945f702e8f05ce0 to your computer and use it in GitHub Desktop.
This code defines a PHP function getYoutubeVideoIdFromUrl that takes a URL as input and attempts to extract a YouTube video ID from it using a regular expression. The function returns the extracted video ID if found or false if no match is found in the input URL. The regular expression is designed to handle various formats of YouTube video URLs.
<?php
/**
* Function to extract a YouTube video ID from a given URL.
*
* @param string $url The input URL that may contain a YouTube video link.
*
* @return string|false If a YouTube video ID is found, it is returned; otherwise, false is returned.
*/
function getYoutubeVideoIdFromUrl($url) {
// Regular expression to match YouTube video URLs
if (preg_match('~
# Match non-linked youtube URL in the wild. (Rev:20130823)
https?:// # Required scheme. Either http or https.
(?:[0-9A-Z-]+\.)? # Optional subdomain.
(?: # Group host alternatives.
youtu\.be/ # Either youtu.be,
| youtube # or youtube.com or
(?:-nocookie)? # youtube-nocookie.com
\.com # followed by
\S* # Allow anything up to VIDEO_ID,
[^\w\s-] # but char before ID is non-ID char.
) # End host alternatives.
([\w-]{11}) # $1: VIDEO_ID is exactly 11 chars.
(?=[^\w-]|$) # Assert next char is non-ID or EOS.
(?! # Assert URL is not pre-linked.
[?=&+%\w.-]* # Allow URL (query) remainder.
(?: # Group pre-linked alternatives.
[\'"][^<>]*> # Either inside a start tag,
| </a> # or inside <a> element text contents.
) # End recognized pre-linked alts.
) # End negative lookahead assertion.
[?=&+%\w.-]* # Consume any URL (query) remainder.
~ix',
$url,
$matches)
) {
// If a match is found, return the extracted YouTube video ID
return $matches[1];
}
// If no match is found, return false
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment