How to extract the parent directory name from a path

For Example let the path be,

$path = “protected/musics/composer/album/song.mp3”;
I can extract the file name with the use of basename() function.
$path = basename($path, “.mp3”);

Also I want to extract the last two directory names in a variable
$composer_name = composer //(extracted from the path $path);
$album_name = album //(extracted from the path $path)

Could you please someone help me out of this? Thanks in advance.

list($composer, $album) = array_slice(explode('/', dirname($path)), -2);

Be sure to keep in mind that maybe the directory separator in your string might be either \ or /

If backslash is a possibility, see preg_split()

thank u so much crmalibu it works. It may be a silly question but I’m a newbie to PHP.

It’s a good question. It was clear, and specific. Bad are questions are like “omg how can i build facebook give me the codez”


For what it’s worth, you could also ‘walk’ up the directory structure grabbing the basename as you go (though a one-liner like crmalibu’s always goes down well).

$path     = "protected/musics/composer/album/song.mp3";
$file     = basename($path, ".mp3"); // song

$path     = dirname($path);
$album    = basename($path); // album

$path     = dirname($path);
$composer = basename($path); // composer

var_dump($file, $album, $composer);
Off Topic:

Regarding “omg how can i build facebook give me the codez”, no-one has ever answered that ‘question’ yet which is probably why it keeps getting asked! (: