tags:

views:

34

answers:

3

Something like:

/directory/a/b - /directory/ = a/b

Is it possible to do this easily?

A: 
echo str_replace("/directory/","","/directory/a/b");

And to use this on other types of strings, your full string goes in the third parameter, and whatever you're "subtracting" goes as the first parameter.

BraedenP
-1 for writing a solution for the pasted code, rather than reading the question -- the OP wants something to work with paths generally, not a simple string replacement, is how I read it.
Jed Smith
+1  A: 

Since you're working with paths, platform sensitivity is important; Windows has a different path separator than most other platforms, and to write reusable code you can't snub a platform.

PHP has a few functions to deal with paths. If you're handed a really strange path like ~foo/bar//bitty/../index.php, use realpath to clean that up for you.

$path = realpath("~foo/bar//bitty/../index.php");
/* output: /home/foo/bar/index.php */

Other functions will aid you -- for example, to get the path part of a filename by itself, use dirname:

print dirname($path);
/* output: /home/foo/bar */

Once you have that, split on the separators and do whatever work you want. The real trick is having PHP worry about all the weirdness in paths for you, and then just working with each part separately. Look into pathinfo and basename as well. I think this is what you were asking for, not how to do dumb string replacements.

Don't forget not allowing injection to your application! Working with paths from Web input is dangerous. Never trust user input.

Jed Smith
But seems you didn't touch about how to do subtraction of path in a general way?
Mask
A: 

Using the dirname() funciton and some strings you can cut the original path up and get the pieces.

<?php
// from:   http://php.net/manual/en/function.dirname.php
$path = "/dirname/a/b";
$dir = dirname(dirname($path)); 
echo "dir at front=$dir\n";
$len = strlen($dir);
$dirname = substr ( $path, 0, $len+1 );
echo "dirname=$dirname\n";
$last_2 = substr ( $path, $len+1 );
echo "last_2=$last_2\n";
?>

results in

$ php x.php
dir at front=/dirname
dirname=/dirname/
last_2=a/b
Philip Schlump