Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last dir from a path in a string

Tags:

php

I am trying to get the last folder name from a path that i store in a string.

e.g: Home/new_folder/test

result = test 
like image 648
Rickstar Avatar asked Jan 19 '11 09:01

Rickstar


People also ask

How do I get the last part of a path?

The first strips off any trailing slashes, the second gives you the last part of the path. Using only basename gives everything after the last slash, which in this case is '' . I initially thought rstrip('/') would be simpler but then quickly realised I'd have to use rstrip(os.

How to get last dir in path Python?

basename(). os. path. basename() - It returns the last part of the path.

How can I get the last part of a path in PHP?

To get the trailing name component of a path you should use basename! In case your path is something like $str = "this/is/something/" the end(explode($str)); combo will fail.

How to get directory from path Python?

dirname() method in Python is used to get the directory name from the specified path. Parameter: path: A path-like object representing a file system path. Return Type: This method returns a string value which represents the directory name from the specified path.


2 Answers

Use basename

basename('Home/new_folder/test'); // output: test 

As a side note to those who answered explode:

To get the trailing name component of a path you should use basename! In case your path is something like $str = "this/is/something/" the end(explode($str)); combo will fail.

like image 66
acm Avatar answered Sep 28 '22 19:09

acm


You can use basename() function:

$last = basename("Home/new_folder/test"); 
like image 39
Kel Avatar answered Sep 28 '22 17:09

Kel