Search code examples
phppathexplode

how to eliminate the first 2 entries from a path in php


i have a variable that shows me the path to a directory like below:

$dir = uploads/sha256/folder1/subfolder1/subsubfolder1

How can i "cut off" the first 2 directories from $dir so that it becomes:

$dir = folder1/subfolder1/subsubfolder1

sample code:

$dir = "uploads/sha256/folder1/subfolder1/subsubfolder1";
$pieces = explode("/", $dir);

echo $pieces[2]; // piece2

This gives me only folder1

And i need the complete path after the sha256 so what i actually try to achieve is something like this:

echo $pieces[>2];

Solution

  • You can capture () everything after the first two directories and replace with that:

    $dir = preg_replace('#[^/]+/[^/]+/(.*)#', '$1', $dir);
    

    Or you can explode it, slice all elements after the first two and implode it again:

    $dir = implode('/', array_slice(explode('/', $dir), 2));