计算相对路径

<form action="04.php" method="post">
	路径1:<input type="text" name="path1"/>
	路径2:<input type="text" name="path2"/><br />
	<input type="submit" value="计算相对路径" />
</form>
<?php

header("Content-type: text/html; charset=utf-8");

echo '<h3>计算相对路径</h3>';


/*
$path1 = ‘e:/php1016/a/b/c/d/file.php’;

$path2 = ‘e:/php1016/a/f/new.php’;

require‘../../../f/new.php’;
计算两个路径的相对路径$path2,$path1的路径

tip:桟

explode
*/


//确定好的用户所填写的路径
! empty($_POST['path1']) ? $path1 = $_POST['path1'] : $path1 = 'e:/php1016/a/b/c/d/file.php';
! empty($_POST['path2']) ? $path2 = $_POST['path2'] : $path2 = 'e:/php1016/a/f/new.php';





//取得文件地址中的目录部分
$dir1 = substr($path1, 0, strrpos($path1, '/'));//dirname();
//'e:/php1016/a/b/c/d/file.php'
//$dir1 = 'e:/php1016/a/b/c/d';

//分割 路径 利用 /
$dir_arr1 = explode('/', $dir1);
//$dir_arr1 = array('e:', 'php1016', 'a', 'b', 'c', 'd');

//$dir2 = 'e:/php1016/a/f/new.php'
$dir_arr2 =  explode('/', $path2);
//$dir_arr2 = array('e:', 'php1016', 'a', 'f', 'new.php');

echo '<hr />';


// 找相同的部分
$same_arr = array();
for($i=0, $len=count($dir_arr1); $i<$len; ++$i ) {
	if( $dir_arr1[$i] == $dir_arr2[$i]) {
		$same_arr[] = $dir_arr1[$i];
	} else {
		break;		// 如果遇到不相同的部分 跳出循环
	}
}

//已经确定了相同的部分
//$same_arr = array('e:', 'php1016', 'a');
//echo  '<hr />';
//print_r($same_arr);

//取得两个路径中不同的部分
$diff1 = array_diff($dir_arr1, $same_arr);
//var_dump($diff1);
//$diff1 = array('b', 'c', 'd');
$diff2 = array_diff($dir_arr2, $same_arr);
//var_dump($diff2);
//$diff2 = array('f', 'new.php');

$diff1 = array_fill(0, count($diff1), '../');
//$diff1 = array('../', '../', '../', );
$diff_str1 = implode('', $diff1);
//$diff_str1 = '../../../';
$diff_str2 = implode('/', $diff2);
$diff_str2 = 'f/new.php';


//echo '<hr />';

//echo $diff_str1 , '<br />';
//echo $diff_str2 , '<br />';

$relative = $diff_str1 . $diff_str2 ;

echo $relative, '<br />';


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值