PHP: Get last directory name from path

谁说胖子不能爱 提交于 2020-04-06 04:38:41

问题


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


回答1:


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




回答2:


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



回答3:


This is the easiest way:

<?php
  echo basename(getcwd());
?>

getcwd() = give your full directory path basename() = give you last directory




回答4:


Try explode('/', '/learnphp/docs/') to split the string into array locations. Then fetch the last location.

Here is more info: http://php.net/manual/en/function.explode.php




回答5:


you can use this simple snippet:

$qa_path=site_root('/learnphp/docs/');
$qa_path = explode("/", $qa_path);
$qa_path = $qa_path[count($qa_path) - 1];



回答6:


$qa_path=explode('/', '/learnphp/docs/');
echo $qa_path[2]; // output docs



回答7:


This will help you

$qa_path=site_root('/learnphp/docs/');
$q_path = explode ("/", $qa_path);
$lastV =  end($q_path);



回答8:


This gives you the current directory name: echo basename(dirname(__FILE__));



来源:https://stackoverflow.com/questions/14285134/php-get-last-directory-name-from-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!