tags:

views:

432

answers:

2

Hey everyone,

I have a full path which I would like to remove certain levels of it. So for instance,

/home/john/smith/web/test/testing/nothing/

I would like to get rid of 4 levels, so I get

/test/testing/nothing/

What would be a good of doing this?

Thanks

+7  A: 

A simple solution is to slice the path up into parts, and then manipulate the array before sticking it back together again:

join("/", array_slice(explode("/", $path), 5));

Of course, if you wanted to remove that specific path, you could also use a regular expression:

preg_replace('~^/home/john/smith/web/~', '', $path);

One word of advice though. If your application is juggling around with paths a lot, it may be a good idea to create a class to represent paths, so as to encapsulate the logic, rather than have a lot of string manipulations all over the place. This is especially a good idea, if you mix absolute and relative paths.

troelskn
Why would you use a needless regular expression? str_replace will do this fine, there is no pattern matching at all!
Jay
Because it's rooted. str_replace will match anywhere in the string, while a regexp which starts with ^ will match only if the string begins with the pattern.
troelskn
Who said he wanted to do that, he wanted to remove parts of the string? Quit giving negative votes simply due to the fact you disagree and aren't willing to step down from your pedestal.
Jay
Quit being childish - It's not pretty.
troelskn
Instead of using / it may be best to use the more portable PATH_SEPARATOR constant
ejunker
A: 

Why are you all using regular expressions for something that requires absolutely no matching; CPU cycles are valuable!

str_replace would be more efficient:

$s_path = '/home/john/smith/web/test/testing/nothing/';
$s_path = str_replace('john/smith/web/test/', '', $s_path);

And use realpath() to resolve any '../../' paths.

And remember dirname(__FILE__) gets the CWD and rtrim() is extremely useful for removing trailing slashes..

Jay
Your solution(s) only works for some subset of valid input. Besides, what makes you think str_replace performs better than a rooted regexp? Did you actually measure the difference? If you did, you would find that the difference is diminutive
troelskn
Maybe once sure, but in a loop it is cumulative.
Jay
Still not important. preg is very efficient. Try measuring it - You'd be surprised.
troelskn