Reputation: 19
Path:
Home/Gallery/Images/Mountains
Last folder name in this path is Mountains and second last folder name is Images.
I want to show this output:
Last folder: Mountains
Second last folder: Images
Is it possible with substr or any another way. Anyone here who can give me answer? Thanks
Upvotes: 1
Views: 1286
Reputation: 14927
Here's a simple option using basename
and dirname
:
$path = 'Home/Gallery/Images/Mountains';
$lastFolder = basename($path);
$secondToLastFolder = basename(dirname($path));
Upvotes: 4
Reputation: 6785
You could split the string on '/' and use array_pop to pop each item out of the resulting array:
$str = "Home/Gallery/Images/Mountains";
$bits = explode("/", $str);
// Gives:
Array
(
[0] => Home
[1] => Gallery
[2] => Images
[3] => Mountains
)
$last = array_pop($bits);
echo 'last: ' .$last; // Mountains
$next = array_pop($bits);
echo 'next: ' .$next; // Images
Upvotes: 1
Reputation: 70
Just 2 small steps:
$path = "Home/Gallery/Images/Mountains";
$parts = explode("/", $path);
$folders = array_slice($parts, -2);
Then, you will have the two folders available in $folders
array
I strongly recommend to read more about array_slice here: https://www.php.net/manual/en/function.array-slice.php
Upvotes: 1