Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Get last directory name from path

Tags:

php

trim

I am writing one function for getting some different database query. Now things are going well but only need to get last directory name from defined path.

$qa_path=site_root('/learnphp/docs/');

I wan to get only docs from above path. Here site_root is nothing but $_SERVER['DOCUMENT_ROOT'] So how can I get only docs ?

Thanks

like image 568
Code Lover Avatar asked Jan 11 '13 19:01

Code Lover


2 Answers

Easiest way would be to use basename($yourpath) as you can see here: http://php.net/basename

like image 179
Till Helge Avatar answered Nov 09 '22 13:11

Till Helge


Provided answer doesn't work if your string contains the file at the end, like :

basename('/home/mypath/test.zip');

gives

test.zip

So if your string contains the file, don't forget to dirname it first

basename(dirname('/home/mypath/test.zip'));

gives

mypath
like image 31
mattspain Avatar answered Nov 09 '22 13:11

mattspain