Reputation: 423
I'm trying to split a URL path into individual strings in an array. I've tried a few things and this is as close as I've gotten:
<?php
$url = '/category/subcategory/item';
$output = array();
$chunks = explode('/', $url);
foreach ($chunks as $i => $chunk)
{
$output[] = sprintf
(
//'<a href="#/%s">%s</a>',
implode('/', array_slice($chunks, 0, $i + 1)),
$chunk
);
}
echo implode(' >> ', $output);
include 'footer.php';
?>
This returns:
/category >> /category/subcategory >> /category/subcategory/item
but I would like to try and return
category >> subcategory >> item
Thanks!
Upvotes: 0
Views: 2976
Reputation: 2247
Why do you implode after exploding? So confusing.
Use this:
$output = explode('/', trim($url, '/'));
echo implode(' >> ', $output);
This removes slashes at the start of the string and at the end.
Upvotes: 0
Reputation: 78994
For your desired output it should be this easy:
$url = '/category/subcategory/item';
$chunks = array_filter(explode('/', $url));
echo implode(' >> ', $chunks);
array_filter
removes the empty element(s).
Combining newboyhun's and Dagon's suggestions:
echo str_replace('/', ' >> ', trim($url, '/'));
Upvotes: 6