PHP will get rid of the full path slash
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.
source to share
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.
source to share