Forum Moderators: coopster

Message Too Old, No Replies

Getting the directory name

My function works...kinda

         

madmatt69

5:35 pm on Aug 19, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hey all,

I'd like to grab the last directory in a file path. For example:
mysite.com/category/sub-category/sub-sub/

I'd like the function to grab the /sub-sub/ part.

Right now I'm using:
$dir = dirname(dirname(__FILE__));

But that returns:
/category/sub-category/

How can I get it to return "sub-sub"?

MattAU

6:17 am on Aug 20, 2008 (gmt 0)

10+ Year Member



You'll probably have to do it manually. Something like the following should work:

$dirs = explode('/',$path);
$last_dir = $dirs[count($dirs) - 2];

$path could be dirname(__FILE__), but that only works if the file you're using is in the sub-sub directory.

eelixduppy

6:18 am on Aug 20, 2008 (gmt 0)



Something like this should work:

function getDirectory($path) {
$path = trim($path, '/');
return substr($path, strrpos($path, '/')+1);
}

You are going to have to change this function around a little bit if the path can use either front of back slashes, which depends on your OS.

Hope this helps.