how to extract the parent directory name from a path

Discussion in 'PHP' started by siva1117, Feb 25, 2010.

  1. #1
    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
    example
    $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.
     
    siva1117, Feb 25, 2010 IP
  2. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #2
    <?php
    
    $path = "protected/musics/composer/album/song.mp3";
    
    //a more effective way to get the actual filename, although not using it, I included it for your future needs.
    $filename = pathinfo($path, PATHINFO_BASENAME);
    
    $directory_parts = explode("/", dirname($path));
    
    $composer_name = $directory_parts[2];
    $album_name = end($directory_parts);
    
    ?>
    PHP:
     
    danx10, Feb 25, 2010 IP
  3. siva1117

    siva1117 Peon

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    thank u so much danx10 it works. It may be a silly question but I'm a newbie to PHP.
     
    siva1117, Feb 25, 2010 IP