Created
May 16, 2025 22:52
-
-
Save bran921007/a81d423bb88ad9bc8e9df5b3111b38fb to your computer and use it in GitHub Desktop.
Youtube url helper functions
This file contains hidden or 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 | |
if (!function_exists('convert_youtube_embed')) { | |
/** | |
* Convert youtube link into embed link. | |
* | |
* @param string $url | |
* | |
* @return string | |
*/ | |
function convert_youtube_embed(string $url) | |
{ | |
return preg_replace( | |
"/\s*[a-zA-Z\/\/:\.]*youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i", | |
"https://www.youtube.com/embed/$2", | |
$url | |
); | |
} | |
} | |
if (!function_exists('in_youtube')) { | |
/** | |
* Check if is youtube link. | |
* | |
* @param string $url | |
* | |
* @return bool | |
*/ | |
function in_youtube(string $url) | |
{ | |
$yt_rx = '/^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/'; | |
//check if is youtube video link | |
if(preg_match($yt_rx, $url, $yt_matches)) { | |
return true; | |
} | |
return false; | |
} | |
} | |
if (!function_exists('get_youtube_id')) { | |
/** | |
* Get youtube ID. | |
* | |
* @param string $url | |
* | |
* @return string | |
*/ | |
function get_youtube_id(string $url) | |
{ | |
$yt_rx = '/^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/'; | |
//check if is youtube video link and return the ID | |
if(preg_match($yt_rx, $url, $yt_matches)) { | |
$videoId = $yt_matches[5]; | |
return $videoId; | |
} | |
return "Youtube Id not found"; | |
} | |
} | |
if (!function_exists('get_youtube_thumbnail')) { | |
/** | |
* Get youtube thumbnail. | |
* | |
* @param string $url | |
* | |
* @return array | |
*/ | |
function get_youtube_thumbnail(string $url) | |
{ | |
$youtubeId = get_youtube_id($url); | |
//'mqdefault.jpg', | |
return "https://i.ytimg.com/vi/{$youtubeId}/mqdefault.jpg"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment