Extract GET Variables from URL String to Array - PHP Function
While making the YouTube Music in MySpace tool, I coudln’t find a function that reads an input URL then makes an array with the GET variable names and values. I needed this to get the video id from the YouTube video URL - so I made it, and now I’m sharing it.
So in my case, the function is fed a YouTube URL and returns the video id variable (v) - So an example:
Input: http://au.youtube.com/watch?v=le860Jd-FqI&feature=related
Output:
$output['v'] = “le860Jd-FqI”
$output['feature'] = “related”
And so witout further ado, here’s the actual code:
function getVariableFromUrl($url) { //we need to see if this URL is passing any GET variables
$variablesStart = strpos($url, "?") + 1;
if (!$variablesStart) {
// no variables!
return(false);
}
//before we extract the variables, we need to remove any anchors
$variablesEnd = strpos($url,"#",$variablesStart);
if ($variablesEnd) {
$getVariables = substr($url, $variablesStart, $variablesEnd - $variablesStart);
} else {
$getVariables = substr($url, $variablesStart);
}
//next, we split the URL into an arrays containing variable name and value pairs (ie. "variable=value")
$variableArray = explode("&", $getVariables);
//we will iterate through each of the array pairs (ie. "variable=value")
foreach ($variableArray as $arraySet) {
$nameAndValue = explode("=", $arraySet);
//using the above examples, $nameAndValue[0] would be “variable” and $nameAndValue[1] would be “value”
$output[$nameAndValue[0]] = $nameAndValue[1];
}
return($output);
}




Piero
could you put your function on a php example, please?? you can email me at piero@chullotv.com
March 18, 2008 @ 5:07 pm
AngusI
Could you not simply have used the extract() function?
April 7, 2008 @ 12:28 am