在这里写一个小功能,需要一些优化帮助!
所有请求都重定向到索引页面,
我有这个函数将一个url解析成一个数组.
网址的类型描述为:
http://localhost/{user}/{page}/?sub_page={sub_page}&action={action}
所以一个例子是:
http://localhost/admin/stock/?sub_page=products&action=add
在请求uri时,域被排除,因此我的函数接受如下字符串:
/admin/stock/?sub_page=products&action=add
我的功能如下,警告它非常程序化.
对于那些无法阅读和理解它的人,我在底部添加了一个解释;)
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;
}
基本上有一个主要的if语句,一个路径是如果没有定义查询字符串(没有’?’),另一个路径是如果’?’确实存在.
我只是想让这个功能变得更好.
是否值得上课?
基本上我需要一个函数,它将/ {user} / {page} /?sub_page = {sub_page}& action = {action}作为参数并返回
array(
"user" => {user},
"page" => {page},
"sub_page" => {sub_page},
"action" => {action}
)
干杯,亚历克斯