Forum Moderators: coopster

Message Too Old, No Replies

Removing extra directory/. 's

Somehow, with preg_replace?

         

adni18

3:15 pm on Jun 12, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi, I was wondering if there's a way to clear all the ../ (up one directory) ticks in a path.

For example, let's say we have the path:

some-dir/joe/../sam/../smith/../jill/

is there a way to simplify that to something like

some-dir/jill

?

Thanks! :D

zulu_dude

3:41 pm on Jun 12, 2006 (gmt 0)

10+ Year Member Top Contributors Of The Month



Well, if you know that the last directory is always going to be off your 'some-dir' (as in your example), then you can simply explode the path by '/' and then tag the last directory onto the base path.

Something like this:

$dirs = explode ("/", $path);
$new_path = $old_base.$dirs[count($dirs)-1];

This is just off the top of my head, so it might not actually work, it's just to give you an idea of what I mean.

If the ..'s are interspersed with directories, then the problem is slightly more complicated and would most likely require some sort of stack system.

adni18

3:59 pm on Jun 12, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yeah, I was thinking of looping through an array like that, and if one of the entries was a .., then zap it and the one before it... that could work. I'll try it! Thanks!

mooger35

4:07 pm on Jun 12, 2006 (gmt 0)

10+ Year Member



I'm not sure if this is what you are looking for but this is what I use to grab just the file name

ex. ../folder1/folder2/folder3/somefile.php

$filename = substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'],'.'));
$page = str_replace("/","",strrchr($filename,'/'));

//returns somefile