PHP: Extract direct sub directory from path string
        Posted  
        
            by Nebs
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Nebs
        
        
        
        Published on 2010-04-30T20:32:27Z
        Indexed on 
            2010/04/30
            20:37 UTC
        
        
        Read the original article
        Hit count: 253
        
I need to extract the name of the direct sub directory from a full path string.
For example, say we have:
$str = "dir1/dir2/dir3/dir4/filename.ext";
$dir = "dir1/dir2";
Then the name of the sub-directory in the $str path relative to $dir would be "dir3". Note that $dir never has '/' at the ends.
So the function should be:
$subdir = getsubdir($str,$dir);
echo $subdir; // Outputs "dir3"
If $dir="dir1" then the output would be "dir2". If $dir="dir1/dir2/dir3/dir4" then the output would be "" (empty). If $dir="" then the output would be "dir1". Etc..
Currently this is what I have, and it works (as far as I've tested it). I'm just wondering if there's a simpler way since I find I'm using a lot of string functions. Maybe there's some magic regexp to do this in one line? (I'm not too good with regexp unfortunately).
function getsubdir($str,$dir) {
    // Remove the filename
    $str = dirname($str);
    // Remove the $dir
    if(!empty($dir)){
        $str = str_replace($dir,"",$str);
    }
    // Remove the leading '/' if there is one
    $si = stripos($str,"/");
    if($si == 0){
        $str = substr($str,1);
    }
    // Remove everything after the subdir (if there is anything)
    $lastpart = strchr($str,"/");
    $str = str_replace($lastpart,"",$str);
    return $str;
}
As you can see, it's a little hacky in order to handle some odd cases (no '/' in input, empty input, etc). I hope all that made sense. Any help/suggestions are welcome.
© Stack Overflow or respective owner