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
Craig
Thank you. Took me ages to find this. Nowhere else has a method like this that I could find.
May 7, 2009 @ 8:09 am
Leonardo
Hi…
Where do you insert the Youtube Video URL.
June 22, 2009 @ 11:07 pm
Tim
The function takes one argument, $url. That’s where the URL goes.
you could use something like this:
$url = $_GET['url'];
$url_variables = getVariableFromUrl[$url];
You will have a 2d array of the get variables from that URL.
July 5, 2009 @ 1:13 am
pmp
Excellent script! Thank you for making it, it saved me a lot of time after screwing with the the parse_url function.
September 16, 2009 @ 1:58 am