计算/a/b/c/d/e.php /a/b/12/34/c.php的父亲路径为/a/b
- <?php
- /*
- *系统环境:windows/linux
- *编译环境:php5/php4
- *输入参数:存放在in.txt,多个参数时空格分隔
- 参数1是一个路径,用\或者/分隔
- 参数2是一个路径,用\或者/分隔
- 参数1,2必须都是绝对路径或者相对路径
- 例如:/a/b/c/d/e.php /a/b/12/34/c.php
- d:\a\b\c\d\e.php d:\a\b\12\34/c.php
- a/b/c/d/e.php a/b/12/34/c.php
- 输出:out.txt
- */
- $params=getParams(2);
- $toParh=trim($params[0]);
- $fromParh=trim($params[1]);
- $toParh=str_replace("\\", "/", $toParh);
- $fromParh=str_replace("\\", "/", $fromParh);
- //linux形式
- if(substr($toParh, 0,1)=="/" || substr($fromParh, 0,1)=="/")
- {
- if(!substr($toParh, 0,1)=="/")
- {
- //若是$toParh是绝对路径,而$fromParh不是绝对路径,报错
- error_msg("两个参数必须都是绝对路径或者相对路径\n");
- }
- if(!substr($fromParh, 0,1)=="/")
- {
- //若是$toParh是绝对路径,而$fromParh不是绝对路径,报错
- error_msg("两个参数必须都是绝对路径或者相对路径\n");
- }
- }
- //windows形式
- if(preg_match("/^[a-z]:/i", $toParh) || preg_match("/^[a-z]:/i", $fromParh))
- {
- if(!preg_match("/^([a-z]):/i", $toParh,$matchs1))
- {
- //若是$toParh是绝对路径,而$fromParh不是绝对路径,报错
- error_msg("两个参数必须都是绝对路径或者相对路径\n");
- }
- if(!preg_match("/^([a-z]):/i", $fromParh,$matchs2))
- {
- //若是$toParh是绝对路径,而$fromParh不是绝对路径,报错
- error_msg("两个参数必须都是绝对路径或者相对路径\n");
- }
- if($matchs1[1]!=$matchs2[1])
- {
- //若是$toParh和$fromParh不在同一个盘里
- error_msg("两个参数必须都是在同一个盘里\n");
- }
- }
- echo getRalationPath($toParh,$fromParh);
- function getRalationPath($toParh,$fromParh)
- {
- $toParh=str_replace("\\", "/", $toParh);
- $fromParh=str_replace("\\", "/", $fromParh);
- $topaths=split("/",$toParh);
- $fromparhs=split("/",$fromParh);
- array_pop($fromparhs);
- array_pop($topaths);
- $relationPath="";
- //去掉相同目录后,计算需要往上的目录级数
- $n=count(array_diff_assoc ($fromparhs,$topaths));
- for($i=0;$i< $n;$i++)
- {
- $relationPath.="../";
- }
- //去掉相同目录后,需要深入的目录
- $digdir=array_diff_assoc ($topaths,$fromparhs);
- $relationPath.=join("/",$digdir);
- return $relationPath;
- }
- /*
- 从in.txt里读取参数
- */
- function getParams($paramNum)
- {
- $in=file_get_contents("in.txt");
- if($in===FALSE){
- error_msg("cannot read in.txt,please check in.txt exists\n");
- }
- $in=preg_replace("/(\s+)/i", " ", $in);
- //多个参数时,按照空格分隔
- $parms=split(" ",trim($in));
- if($parms===FALSE)
- {
- error_msg("cannot get param from in.txt\n");
- }
- if(count($parms) < $paramNum)
- {
- error_msg("it needs $paramNum params\n");
- }
- return $parms;
- }
- /*
- 把结果输出到输出文件里
- 当isClean=true时清空out.txt
- */
- function output($msg,$isClean=false)
- {
- if($isClean)
- {
- $handle = fopen('out.txt', 'w');
- fclose($handle);
- }
- error_log($msg."\n", 3, "out.txt");
- }
- /*
- 输入错误信息
- 如果$is_exit表示输入信息后退出
- */
- function error_msg($msg,$is_exit=true)
- {
- if($is_exit)
- die($msg."\n");
- else
- echo $msg."\n";
- }
- ?>
本文转自yifangyou 51CTO博客,原文链接: 本文转自yifangyou 51CTO博客,原文链接:,如需转载请自行联系原作者
,如需转载请自行联系原作者