Search code examples
phppathsplit

How to split a path properly in PHP


What is the best way to do the following:

I get a path with an AJAX request

e.g. dir1/dir2/dir3/dir4

I need to present it like this on my webpage:

dir1 >> dir2 >> dir3 >> dir4

each of them being html anchor tags with the href attribute being

/dir1

/dir1/dir2

/dir1/dir2/dir3

/dir1/dir2/dir3/dir4 

respectively

What is the most elegant and efficient way to achieve this?

so far, I'm doing something like this which i think is really dirty:

<?php 
$dirs = explode(PATH_SEPARATOR, $this->metadata["path"]);
    foreach ($dirs as $key=>$val) {
             if ($val == '') {
                 continue;
             }
             $pathArray = array();
             for ($i = 0; $i <= $key; $i++) {
                 array_push($pathArray, $dirs[$i]);
             }
             $path = implode('/', $pathArray);
             echo " >> <a href=" . $path . ">" . truncate($val) . "</a>";
    }
    ?>  

Solution

  • Something like this maybe (if I got your intention right):

    <?php
    $str = 'dir1/dir2/dir3/dir4';
    
    $output = array();
    $chunks = explode('/', $str);
    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);
    

    Output:

    <a href="#/dir1">dir1</a> &gt;&gt; 
    <a href="#/dir1/dir2">dir2</a> &gt;&gt;
    <a href="#/dir1/dir2/dir3">dir3</a> &gt;&gt;
    <a href="#/dir1/dir2/dir3/dir4">dir4</a>