Jason Behtel
Jason Behtel

Reputation: 35

From a filepath string, get only the directory path of the parent directory

so I am trying to learn some string functions in PHP and came across a scenario I cannot figure out. I want to take a string like such: /var/www/html and remove everything after the last forward slash (including the forward slash) so I end up with /var/www

What would be the best way to go about this?

Upvotes: 2

Views: 60

Answers (2)

Jimmy Sawczuk
Jimmy Sawczuk

Reputation: 13614

This should work:

$str = substr($str, 0, strrpos($str, '/') - 1);

...but see icktoofay's solution if you're only planning on using this to handle file paths.

Upvotes: 1

icktoofay
icktoofay

Reputation: 128991

Try using dirname. It may handle special cases for you that you may not have anticipated if you went with a string manipulation route.

Upvotes: 4

Related Questions