PHP will get rid of the full path slash

I have a complete path that I would like to remove from it. For example,

/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 helpful for this?

thank

+1


source to share


2 answers


A simple solution is to cut the path into pieces and then manipulate the array before inserting it back again:

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

      

Of course, if you want to remove that specific path, you can also use a regex:



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

      

One word of advice though. If your application juggles a lot with paths, it might be a good idea to create a class to represent paths to encapsulate the logic, rather than have a lot of string manipulation all over the place. This is a particularly good idea if you are mixing absolute and relative paths.

+7


source


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

str_replace will 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 solve any '../../'

path.

And remember what dirname(__FILE__)

gets CWD and is rtrim()

extremely useful for removing trailing slashes.

-2


source







All Articles