Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplifying a directory string

Tags:

html

php

Take the following directory structure:

  • Parent1
    • Child folder
      • Child Folder 1
      • Child Folder 2

The path to Child Folder 2 would be:

Parent/Child folder/Child Folder 2

But, another valid path can also be

Parent/Child folder/Child Folder 1/../Child Folder 2

Is there a way to "Simplify" the path, or convert a path such as:

Parent/Child folder/Child Folder 1/../Child Folder 2

to

Parent/Child folder/Child Folder 2

I was trying to find a way to extract the file name from the handle that opendir($directory) gives you, but I haven't found a way to do this yet. I'm also pretty sure there must be some terminology or better wording than "simplify", but I did not know what to search for. "Simplify path" php didn't help much.

Edit:

I've noticed realpath gives me the complete, full path. It does not give you the relative one, as in Parent/Child folder/Child Folder 2, but C:\Path\To\Server\Directory\Parent\Child Folder\Child Folder 2 That's a bit disappointing, but I can convert it back with some string manipulation.

like image 664
David Avatar asked Jul 29 '26 04:07

David


2 Answers

If the path actually exists, you can use realpath() to resolve relative path portions. It also resolves symbolic links.

like image 50
alex Avatar answered Jul 31 '26 17:07

alex


Try realpath()

$path = realpath('Parent/Child folder/Child Folder 1/../Child Folder 2');
like image 39
John Conde Avatar answered Jul 31 '26 16:07

John Conde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!