Calculates the relative path of path A for path b

Source: Internet
Author: User
Tags explode

The format of the---csdn is really dt-_-

<?php
/**
 * Calculation path a relative path to path b * @author wusuopubupt * * @date 2013-08-01 * * * * * * * * * * * *
$dira = '/a/e.php ';
$DIRB = '/a/b/f/e/g.php ';

Explode directions
$arr _dira = explode ('/', $dira);
$arr _DIRB = explode ('/', $DIRB);

$count _a = count ($arr _dira);
$count _b = count ($arr _dirb);
$max = max ($count _a, $count _b);

$count =0;
for ($i = 0; $i < $max; $i + +) {
    if (isset ($arr _dira[0]) && isset ($arr _dirb[0)) && $arr _dira[0] = = $ Arr_dirb[0]) {
        array_shift ($arr _dira);
        Array_shift ($arr _DIRB);
        $count + +;
    }
}

$relative _path = Str_repeat ('.. /', $count _a-$count);
Echo $relative _path. Implode ('/', $arr _DIRB). "\ n";
? >

The basic idea: first put the A,B2 path with/split the number of groups, define count = 0, starting from subscript 0 to traverse 2 arrays, if arr_a[0] = = Arr_b[0], then use Array_shift () to delete the first value of the array, at this time count+1, Continue the loop until it is not equal, at which point the array B is left with a,b parts. Subtracting count from the length of the array A is the number of paths a reached the a,b common path. Like 2 times, just use. /.. /represented, then, using/connecting array B, you can get a relative to B path
Reference:
1. Heuristic but faulty algorithm: http://istrone.com/?p=1165
2.array_pop Usage: http://www.php.net/manual/zh/function.array-pop.php
3.array_shift Usage: http://www.php.net/manual/zh/function.array-shift.php
4.array_diff (): Calculates the difference set for a 2 array
Array_intersect (): Intersection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.