Skip to content

Instantly share code, notes, and snippets.

@dellow
Last active October 5, 2021 10:09
Show Gist options
  • Save dellow/16f713efa16687225a92 to your computer and use it in GitHub Desktop.
Save dellow/16f713efa16687225a92 to your computer and use it in GitHub Desktop.
Extracts a YouTube iframe video from a string.
/**
* extract_youtube_video
* Extracts a YouTube iframe video from a string.
*
* @since 1.0.0
* @version 1.0.0
**/
function extract_youtube_video($string, $decode = true){
// Decode string.
$content = ($decode) ? html_entity_decode($string, ENT_QUOTES, 'utf-8') : $string;
// Search for iframe.
if(strpos($content, 'iframe') !== false){
// Use PHP DOMDocument.
$doc = new DOMDocument();
// Get HTML.
$doc->loadHTML($content);
// Get video source.
$youtube = $doc->getElementsByTagName('iframe')->item(0)->getAttribute('src');
// Find opening position of iframe.
$pos1 = strpos($content, '<iframe');
// Find closing position of iframe.
$pos2 = strpos($content, '</iframe>');
// Get string to remove.
$len = $pos2 - $pos1;
// Create YouTube video.
$youtube = '<div class="embed-container"><iframe src="' . $youtube . '" frameborder="0" allowfullscreen></iframe></div>';
// Replace current iframe with modified one.
$replaced = substr_replace($content, $youtube, $pos1, $len);
// Return new responsive embed string with rest of text applied.
return $replaced;
}
// If no iframe, return string as required.
else{
return ($decode) ? html_entity_decode($string, ENT_QUOTES, 'utf-8') : $string;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment