Alfred
Alfred

Reputation: 21386

Remove root directory from a directory path string - PHP

I have a variable like $path = "dir1/dir2/dir1/dir4/"; etc.. etc..

I want to remove the first member dir1/ and want result like dir2/dir1/dir4/.

I think it is possible by making the variable an array by explode('/', $path). How can I remove the first member vrom array and reconstruct that array into a text variable??

How can I achieve this in PHP?

Upvotes: 3

Views: 7079

Answers (4)

Menztrual
Menztrual

Reputation: 41587

$result = explode("/", $path); // Pull it apart
array_shift($result); // Pop the first index off array
$result = implode("/", $result); // Put it together again

Upvotes: 1

Shakti Singh
Shakti Singh

Reputation: 86336

According to your updated question

Only explode into two parts, take the second one. In case the second one does not exists, give it NULL:

list(, $result) = explode("/", $path, 2) + array( 1 => NULL);

OR

$array = explode("/", $path);
unset($array[0]);
echo $text = implode("/", $array);

Upvotes: 8

meze
meze

Reputation: 15087

preg_replace('~^[^/]+/~', '', $path);

or if you don't want regexp:

substr($path, strpos($path, '/') + 1);

Upvotes: 5

heyanshukla
heyanshukla

Reputation: 669

You can do like that $result= explode("/", $path);. You will get result as an array.

Upvotes: 0

Related Questions