Home >php教程 >PHP源码 >新浪一道面试题:写一个函数,算出两个文件的相对路径。

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

PHP中文网
PHP中文网Original
2016-05-25 17:10:361056browse


<?php
$a = &#39;aa/bb/cc/dd/a.php&#39;;
$b =&#39;aa/bb/11/22/33/b.php&#39;;

//写一个函数,数出二个文件的相对路径。
function GetNum($variant,$variant2){
	$pth1 = null;
	$pth2 = null;
	$tmp = array();
	//分别判断路径下面的文件是不是存在.
	if(is_file($variant) && is_file($variant2)){
		$len1 = count($pth1 = explode(&#39;/&#39;,dirname($variant))); 	
		$len2 = count($pth2 = explode(&#39;/&#39;,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 .= &#39;../&#39;;
			}
		}
		return $pathe.implode(&#39;/&#39;,$tmp).&#39;/&#39;.basename($variant2);
	}else{
		return &#39;路径不合法!&#39;;
	}

}

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

                   

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn