To get this pages "You are here" it would read the following;
HOME => questions => 28240416 => php-split-url-to-create-you-are-here-navigation
I would like to use PHP to get the URL and split after the domain name separating all via the forward slash '/' to create a "You are here" content.
In addition I would like to replace all '-', '_', '%20' with ' ' and capitalize the first letter of the split.
Mock URL Examples;
URL: https://stackoverflow.com/users/4423554/tim-marshall
Would return;
Home => Users => 4423554 => Tim-marshall
My latest attempt has only produces the last part of the string;
<?php
$url = "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";;
$parts = explode('/', rtrim($url, '/'));
$id_str = array_pop($parts);
// Prior to 5.4.7 this would show the path as "//www.example.com/path"
echo '<h1>'.$id_str.'</h1>';
?>
<?php
$url = 'somedomainDOTcom/animals/dogs';
$arr = explode($url, '/');
unset($arr[0]);
$title = '';
foreach($arr as $v) $title .= ucfirst($v).'>>';
$title =trim($title,'>');
echo "
<br>".$title;
?>
Use explode
, array_unshift
, array_map
, ucfirst
, and implode
:
$url = '/this/is/the/path'; // or $_SERVER['REQUEST_URI'].. avoid $_SERVER['HTTP_HOST']
$url = str_replace(array('-', '_', '%20'), ' ', $url); // Remove -, _, %20
// your choice of removing extensions goes here
$parts = array_filter(explode('/', $url)); // Split into items and discard blanks
array_unshift($parts, 'Home'); // Prepend "Home" to the output
echo implode(
' => ',
array_map(function($item) { return ucfirst($item); }, $parts)
); // Capitalize and glue together with =>
Output:
Home => This => Is => The => Path
or in resolved HTML:
Home => This => Is => The => Path
Removing extensions is the trickier part if you have stray dots in the URI. If it's a guarantee that only the filename will have the dot, you can use:
$url = explode('.', $url);
$url = $url[0]; // Returns the left half
but if there's no guarantee, and you know what the possible extensions are, you can just use str_replace
again:
$url = str_replace(array('.php','.html','.whatever'), '', $url);
but since you're only going to be running this script in the PHP, context, it's probably as simple as:
$url = str_replace('.php', '', $url)
<?php
$url = "testdomain.com/Category/Sub-Category/Files.blah";;
$chunks = array_filter(explode('/', $url));
echo "<h1>".implode(' >> ', $chunks)."</h1>";
?>
For your current page, replace
$url = "testdomain.com/Category/Sub-Category/Files.blah";
With
$url = "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
And it will return your "Where are you" Navigation.