Strip out YouTube code from the URL
Big thanks to Kris Noble for this snippet of code. If you are setting up a CMS for a client which includes a video of sorts – you may wish to keep the ratio and dimensions, but allow them to change the code through the CMS. This function below strips out the required code from …
Big thanks to Kris Noble for this snippet of code.
If you are setting up a CMS for a client which includes a video of sorts – you may wish to keep the ratio and dimensions, but allow them to change the code through the CMS. This function below strips out the required code from the URL so that the client doesn’t have to. If the client does paste in just the code – it picks that up as well and uses it.
[php]
function get_youtube_id($ytURL)
{
// Adapted from http://snipplr.com/view.php?codeview&id=19232
$ytvIDlen = 11; // This is the length of YouTube’s video IDs
$ytURL = str_replace(‘http://youtu.be/’, ”, $ytURL);
// Accounts for short youtube URL
if(strlen($ytURL) == $ytvIDlen)
{
// probably already a valid id
return $ytURL;
}
// The ID string starts after "v=", which is usually right after
// "youtube.com/watch?" in the URL
$idStarts = strpos($ytURL, "?v=");
// In case the "v=" is NOT right after the "?" (not likely, but I like to keep my
// bases covered), it will be after an "&":
if($idStarts === FALSE)
{
$idStarts = strpos($ytURL, "&v=");
}
// If still FALSE, URL doesn’t have a vid ID
if($idStarts === FALSE)
{
// some kind of ‘Please enter a valid YouTube video ID or URL’ validation message here maybe..
return FALSE;
}
// Offset the start location to match the beginning of the ID string
$idStarts +=3;
// Get the ID string and return it
$ytvID = substr($ytURL, $idStarts, $ytvIDlen);
return $ytvID;
}
[/php]
For example, in your CMS you might have a field titled ‘Youtube Video’ where the user pastes in the URL to the video.
On your front end you will then have code similar to this:
[php]
<?php $videoID = get_youtube_id($youtubeVideo);
if($videoID) { ?>
<iframe width="357" height="222" src="http://www.youtube.com/embed/<?=$videoID?>" frameborder="0" allowfullscreen></iframe>
<?php } ?>
[/php]
In other words – if there is a youtube video content, show the above code and place the youtube video ID in the correct place.
Below is a minified version of the function
[php]
function get_youtube_id($ytURL) {
$ytvIDlen = 11;
$ytURL = str_replace(‘http://youtu.be/’, ”, $ytURL);
if(strlen($ytURL) == $ytvIDlen) {return $ytURL;}
$idStarts = strpos($ytURL, "?v=");
if($idStarts === FALSE) { $idStarts = strpos($ytURL, "&v=");}
if($idStarts === FALSE) { return FALSE;}
$idStarts +=3;
$ytvID = substr($ytURL, $idStarts, $ytvIDlen);
return $ytvID;
// Thanks to Kris Noble and http://snipplr.com/view.php?codeview&id=19232 for this
}
[/php]