Just writing a little function here and need some optimisation help!
All requests redirect to the index page,
I have this function that parses a url into an array.
The type of url is depicted as:
http://localhost/{user}/{page}/?sub_page={sub_page}&action={action}
So an example would be:
http://localhost/admin/stock/?sub_page=products&action=add
When requesting the uri the domain is excluded so my function accepts strings like so:
/admin/stock/?sub_page=products&action=add
My function is as follows and WARNING it's very procedural.
for those of you that cannot be bothered to read and understand it, ive added an explaination at the bottom ;)
function uri_to_array($uri){
// uri will be in format: /{user}/{page}/?sub_page={subpage}&action={action} ... && plus additional parameters
// define array that will be returned
$return_uri_array = array();
// separate path from querystring;
$array_tmp_uri = explode("?", $uri);
// if explode returns the same as input $string, no delimeter was found
if ($uri == $array_tmp_uri[0]){
// no question mark found.
// format either '/{user}/{page}/' or '/{user}/'
$uri = trim($array_tmp_uri[0], "/");
// remove excess baggage
unset ($array_tmp_uri);
// format either '{user}/{page}' or '{user}'
$array_uri = explode("/", $uri);
// if explode returns the same as input $string, no delimiter was found
if ($uri == $array_uri[0]){
// no {page} defined, just user.
$return_uri_array["user"] = $array_uri[0];
}
else{
// {user} and {page} defined.
$return_uri_array["user"] = $array_uri[0];
$return_uri_array["page"] = $array_uri[1];
}
}
else{
// query string is defined
// format either '/{user}/{page}/' or '/{user}/'
$uri = trim($array_tmp_uri[0], "/");
$parameters = trim($array_tmp_uri[1]);
// PARSE PATH
// remove excess baggage
unset ($array_tmp_uri);
// format either '{user}/{page}' or '{user}'
$array_uri = explode("/", $uri);
// if explode returns the same as input $string, no delimiter was found
if ($uri == $array_uri[0]){
// no {page} defined, just user.
$return_uri_array["user"] = $array_uri[0];
}
else{
// {user} and {page} defined.
$return_uri_array["user"] = $array_uri[0];
$return_uri_array["page"] = $array_uri[1];
}
// parse parameter string
$parameter_array = array();
parse_str($parameters, $parameter_array);
// copy parameter array into return array
foreach ($parameter_array as $key => $value){
$return_uri_array[$key] = $value;
}
}
return $return_uri_array;
}
basically there is one main if statement, one path is if no querystring is defined (no '?') and the other path is if the '?' does exist.
I'm just looking to make this function better.
Would it be worth making it a class?
Essentially i need a function that takes /{user}/{page}/?sub_page={sub_page}&action={action} as an argument and returns
array(
"user" => {user},
"page" => {page},
"sub_page" => {sub_page},
"action" => {action}
)
Cheers, Alex
parse_url()to simplify some tasks.preg_match()for your desired pattern serve the same purpose?