I am currently using the following code to achieve a page, section and class variable from the 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;
}
For example if the url is http://www.mydomain.co.uk/about/ the code will return the following variables:
$page = "about"
$section = "about"
$class = "about"
For http://www.mydomain.co.uk/about/general-info/
$page = "general info"
$section = "about"
$class = "about general-info"
But when I add more depth for example For http://www.mydomain.co.uk/about/general-info/history/ to code produces:
$page = "history"
$section = "general info"
$class = "general-info history"
where ideally I need it to output the following:
$page = "history"
$section = "about general info"
$class = "about general-info history"
or breakdown the sections into as many as needed for example:
$section1 = "about"
$section2 = "general-info"
Hopefully someone can help. If anything is unclear please ask.
So you want an URI-scheme as follows?
Special cases:
Instead of relying on
basename(), you should split your string into an array usingexplode()orpreg_split(). You can useREQUEST_URIdirectly since the domain name does not give any extra information for your sections and page.Once you have an array, you can easily
count()the number of path components, handle special cases for empty and size-one paths, and so on. In the following example, I usearray_pop()to extract the last part of the path to separate the page from the sections. Since you seem to desire space-separated strings for sections and page, I useimplode()to join the arrays back into a string.