开发者

How to conduct File path operation in PHP?

开发者 https://www.devze.com 2022-12-11 13:55 出处:网络
Something like: /directory/a/b - /directory/ = a/b Is it possible to do this easily开发者_StackOverflow?Since you\'re working with paths, platform sensitivity is important; Windows has a different

Something like:

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

Is it possible to do this easily开发者_StackOverflow?


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.


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号