如何解决使用php将URL拆分为页面和文件夹变量?
| 我目前正在使用以下代码从url实现页面,节和类变量。$domain = \'http://\' . $_SERVER[\'HTTP_HOST\'];
$path = $_SERVER[\'REQUEST_URI\'];
$url = $domain . $path;
// page + section + class
$page = basename($url);
$page = $class = str_replace(\'.php\',\'\',$page);
$page = str_replace(\'-\',\' \',$page);
if ($path == \"/\") {
$section = $class = \"home\";
} else if (basename(dirname($url),\"/\") == $_SERVER[\'HTTP_HOST\']) {
$section = $page;
} else {
$section = basename(dirname($url),\"/\");
$section = str_replace(\'-\',$section);
$class = basename(dirname($url),\"/\") . \" \" . $class;
}
例如,如果URL为“ 1”,则代码将返回以下变量:
$page = \"about\"
$section = \"about\"
$class = \"about\"
对于http://www.mydomain.co.uk/about/general-info/
$page = \"general info\"
$section = \"about\"
$class = \"about general-info\"
但是,例如,当我添加更多深度时,对于代码http://www.mydomain.co.uk/about/general-info/history/
会产生:
$page = \"history\"
$section = \"general info\"
$class = \"general-info history\"
理想情况下,我需要它来输出以下内容:
$page = \"history\"
$section = \"about general info\"
$class = \"about general-info history\"
或将这些部分细分为所需的数量,例如:
$section1 = \"about\"
$section2 = \"general-info\"
希望有人可以提供帮助。如果不清楚,请询问。
解决方法
因此,您需要以下URI方案吗?
http://<domain>/<section-1>/<section-2>/.../<page>/
特别案例:
(1) http://<domain>/ -- page is empty,section is \"home\"
(2) http://<domain>/<section>/ -- page and section are \'<section>\'
而不是依赖于basename()
,您应该使用explode()
或preg_split()
将字符串拆分为一个数组。您可以直接使用“ 14”,因为域名不会为您的栏目和页面提供任何其他信息。
拥有数组后,您可以轻松地将路径分量的数量减少15倍,处理空路径和大小一的路径的特殊情况,等等。在下面的示例中,我使用ѭ16来提取路径的最后一部分,以将页面与各节分开。由于您似乎需要用空格分隔的部分和页面字符串,因此我使用implode()
将数组重新组合成字符串。
// No need for the domain stuff!
$path = $_SERVER[\'REQUEST_URI\'];
// Split at \'/\',could use explode() but the PREG_SPLIT_NO_EMPTY flag is
// very handy since it handles \"//\" and \"/\" at start/end.
$tokens = preg_split(\'#/#\',$path,-1,PREG_SPLIT_NO_EMPTY);
if (count($tokens) == 0) {
// Special case 1
$page = \"\";
$section = $class = \'home\';
} elseif (count($tokens) == 1) {
// Specical case 2
$page = $section = $class = $tokens[0];
} else {
// Class contains all tokens.
$class = implode(\' \',$tokens);
// The last part is the page.
$page = array_pop($tokens);
// Everything else are sections.
$sections = implode(\' \',$tokens);
}
// You seem to want spaces for dashes in the section:
$section = str_replace(\'-\',\' \',$section);
,使用更一般的分割怎么样?
// Url: http://www.mydomain.co.uk/about/general-info/history/
$slices = explode(\'/\',$_SERVER[\'REQUEST_URI\']);
// $slices == [\'about\',\'general-info\',\'history\']
然后根据需要进行路由:
$class = implode(\' \',$slices);
$section = $slices[1];
// etc.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。