I'm trying to create a function that calls a value from a Wordpress custom field ("_videourl" for a YouTube video URL) and then uses PHP trim to cut it down to just the YouTube video ID. I found a javascript function that cuts down URLs to just the ID but I have no idea how I'd be able to translate that into php (function below):
function youtubeIDextract(url)
{
var youtube_id;
youtube_id = url.replace(/^[^v]+v.(.{11}).*/,"$1");
return youtube_id;
}
This PHP function would be used inside the loop so I think I would have to use variables, but I'm really just a noob so I have no idea what to do. Can anyone help by sharing their coding expertise in helping me create a PHP function?
EDIT:SOLVED
After some experimentation, I found a solution. I wanted to return and post it so that others also in need would have somewhere to start from.
function getYoutubeId($ytURL)
{
$urlData = parse_url($ytURL);
//echo '<br>'.$urlData["host"].'<br>';
if($urlData["host"] == 'www.youtube.com') // Check for valid youtube url
{
$ytvIDlen = 11; // This is the length of YouTube's video IDs
// 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)
die("YouTube video ID not found. Please double-check your URL.");
// 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;
}
else
{
//echo 'This is not a valid youtube video url. Please, give a valid url...';
return 0;
}
}