欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

新浪一道面试题:写一个函数,算出两个文件的相对路径。

程序员文章站 2022-04-06 09:59:21
...
<?php
$a = 'aa/bb/cc/dd/a.php';
$b ='aa/bb/11/22/33/b.php';

//写一个函数,数出二个文件的相对路径。
function GetNum($variant,$variant2){
	$pth1 = null;
	$pth2 = null;
	$tmp = array();
	//分别判断路径下面的文件是不是存在.
	if(is_file($variant) && is_file($variant2)){
		$len1 = count($pth1 = explode('/',dirname($variant))); 	
		$len2 = count($pth2 = explode('/',dirname($variant2))); 
		$maxlen = max($len1,$len2);
		for($i=1;$i<$maxlen;$i++){
			if($pth1[$i] != $pth2[$i] && isset($pth1[$i])){
				if(isset($pth2[$i])) $tmp[] = $pth2[$i];
			}else{
				$tmp[] = $pth2[$i];
				$pathe .= '../';
			}
		}
		return $pathe.implode('/',$tmp).'/'.basename($variant2);
	}else{
		return '路径不合法!';
	}

}

print_r(GetNum($a,$b));