Home > php教程 > php手册 > PHP函数计算两个文件的相对路径

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

WBOY
Release: 2016-06-21 08:51:28
Original
1284 people have browsed it

 

  新浪有个面试题目:写一个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));

  ?>



Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template