Heim  >  Artikel  >  php教程  >  PHP函数计算两个文件的相对路径

PHP函数计算两个文件的相对路径

WBOY
WBOYOriginal
2016-06-21 08:51:281224Durchsuche

 

  新浪有个面试题目:写一个php函数算出两个文件的相对路径 ?php //计算出 c.php相对于e.php的相对路径应该是../../12/34 $a = /a/b/c/d/e.php; $b = /a/b/12/34/c.php; getpathinfo($a, $b); function getpathinfo( $a, $b ) { $a

  新浪有个面试题目:写一个php函数算出两个文件的相对路径

  

  //计算出 c.php相对于e.php的相对路径应该是../../12/34

  $a = '/a/b/c/d/e.php';

  $b = '/a/b/12/34/c.php';

  getpathinfo($a, $b);

  function getpathinfo( $a, $b ) {

  $a2array = explode('/', $a);

  $b2array = explode('/', $b);

  $pathinfo = '';

  for( $i = 1; $i

  $pathinfo.=$a2array[$i] == $b2array[$i] ? '../' : $b2array[$i].'/';

  }

  print_R($pathinfo);

  }

  ?>

  还有个比较复杂的方法不太完善思路是正确的可以研究

  

  $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

  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));

  ?>



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:PHP实现短网址开源API,不需DBNächster Artikel:5个 PHP 安全措施