<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 />';