totalfreakingnoob
totalfreakingnoob

Reputation: 423

How to split a URL on forward slashes

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(' &gt;&gt; ', $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

Answers (2)

D&#225;vid Szab&#243;
D&#225;vid Szab&#243;

Reputation: 2247

Why do you implode after exploding? So confusing.

Use this:

$output = explode('/', trim($url, '/'));
echo implode(' &gt;&gt; ', $output);

This removes slashes at the start of the string and at the end.

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

For your desired output it should be this easy:

$url = '/category/subcategory/item';
$chunks = array_filter(explode('/', $url));
echo implode(' &gt;&gt; ', $chunks);

array_filter removes the empty element(s).

Combining newboyhun's and Dagon's suggestions:

echo str_replace('/', ' &gt;&gt; ', trim($url, '/'));

Upvotes: 6

Related Questions