Home > Backend Development > PHP Tutorial > How to calculate the relative path of a file in php

How to calculate the relative path of a file in php

墨辰丷
Release: 2023-03-31 19:08:01
Original
1867 people have browsed it

This article mainly introduces the method of PHP calculating the relative path of two files, involving the skills of PHP operating strings, and has certain reference value. Friends in need can refer to it

The examples in this article describe PHP Method to calculate the relative paths of two files. Share it with everyone for your reference. The details are as follows:

1. Question:

Write a php function to calculate the relative paths of two files. For example, $a="/a/b/c/d/e.php"; $b="/a/b/12/34/c.php", what is the relative path of B relative to A?

2. Solution:

<?php
/**
 * 求$b相对于$a的相对路径
 * @param string $a
 * @param string $b
 * @return string
 */
function getRelativePath ($a, $b)
{
  $patha = explode(&#39;/&#39;, $a);
  $pathb = explode(&#39;/&#39;, $b);
  $counta = count($patha) - 1;
  $countb = count($pathb) - 1;
  $path = "../";
  if ($countb > $counta) {
    while ($countb > $counta) {
      $path .= "../";
      $countb --;
    }
  }
  // 寻找第一个公共结点
  for ($i = $countb - 1; $i >= 0;) {
    if ($patha[$i] != $pathb[$i]) {
      $path .= "../";
      $i --;
    } else {
//判断是否为真正的第一个公共结点,防止出现子目录重名情况
      for ($j = $i - 1, $flag = 1; $j >= 0; $j --) {
        if ($patha[$j] == $pathb[$j]) {
          continue;
        } else {
          $flag = 0;
          break;
        }
      }
      if ($flag)
        break;
      else
        $i ++;
    }
  }
  for ($i += 1; $i <= $counta; $i ++) {
    $path .= $patha[$i] . "/";
  }
  return $path;
}
$a = "/a/c/d/e.php";
$b = "/a/c.php";
$path = getRelativePath($a, $b);
echo $path;
Copy after login

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

Brief description of PHP date function and method of obtaining set time

Application of PHP file operation function

Reference implementation tree generation method in PHP

The above is the detailed content of How to calculate the relative path of a file in php. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template