时间:2021-07-01 10:21:17 帮助过:15人阅读
1 6 * @version $Id:v 1.0 ,2013/10/13 17:29:00 7 * @copyright (c) Copyright;tsingyuan,2013 8 */ 9 10 /** 11 * 返回文件的绝对路径 12 * 13 * @param string $filename 14 * @return string 15 */ 16 function absoluteroute($filename) 17 { 18 $split = '/\/|\\\/'; 19 $currentdir = preg_split($split, dirname(__FILE__)); 20 $dirarr = preg_split($split, $filename); 21 $diracount = count($dirarr); 22 $cda = count($currentdir); 23 if(strpos(PHP_OS, 'WIN') !== false) 24 $reg = '/\w\:/'; 25 else 26 $reg = '/\//'; 27 if(!preg_match($reg, $dirarr[0])) 28 { 29 foreach($dirarr as $nk=>$name) 30 { 31 if($name == "." || $name == '..') 32 { 33 if($name == '..') 34 $filenamearr = array_slice($currentdir, 0, -($nk+1)); 35 if($name == '.' && $nk == '0') 36 $filenamearr = array_slice($currentdir, 0); 37 } 38 else 39 { 40 $filenamearr[] = $name; 41 } 42 } 43 $filename = implode('/', $filenamearr); 44 } 45 return $filename; 46 } 47 48 /** 49 * 返回两个文件的相对路径 (PS:^_^不错的php学习交流群:276167802,验证:csl,有兴趣的话可以加入进来一起讨论) 50 * (为了保证输入的相对路径参数可用,故此函数依赖absoluteroute) 51 * 52 * @param string $filenamea 53 * @param string $filenameb 54 * @return string 55 */ 56 function relativeroute($filenamea, $filenameb) 57 { 58 $split = '/\/|\\\/'; 59 $filenamea = absoluteroute($filenamea); 60 $filenameb = absoluteroute($filenameb); 61 $dira =preg_split($split, $filenamea); 62 $dirb =preg_split($split, $filenameb); 63 $flag = true; 64 if(count($dira) >= count($dirb)) 65 { 66 $tmp = array(); 67 $tmp = $dira; 68 $dira = $dirb; 69 $dirb = $tmp; 70 $flag = false; 71 } 72 foreach($dira as $k=>$v) 73 if($v != $dirb[$k])break; 74 75 $dirr = array_slice($dirb, $k); 76 77 $k == 1 ? $dtag = '/' : $dtag = './'; 78 $result = $dtag.implode('/', $dirr); 79 if(!$flag) 80 { 81 if($dira[0] == '')array_shift($dira); 82 foreach($dirr as $kk=>&$v) 83 ($kk+1) != count($dirr)? 84 ($v ? 85 $v = '..' : 86 $v = '.' 87 ) : 88 $v = implode('/', array_slice($dira, $k)) ; 89 $result = $dtag.implode('/', $dirr); 90 } 91 return $result; 92 }