Research on small relative paths
For example, find the relative path of the two paths and make a brick!
- /**
- * Find the relative path of the two paths
- * @ Param string $ patha path
- * @ Param string $ pathb path B
- * @ Author Joychao
- * @ Link http://www.joychao.cc
- * @ Return string relative path
- */
- Function getRelativePath ($ patha, $ pathb ){
- $ Arr_a = explode ('/', trim (dirname ($ patha ),'/'));
- $ Arr_ B = explode ('/', trim (dirname ($ pathb ),'/'));
- $ N = min (count ($ arr_a), count ($ arr_ B); // use the shortest path to loop
- $ Flag = true; // tag bit [whether the tag has no intersection at all]
- For ($ I = 0; $ I <$ n; $ I ++ ){
- If ($ arr_a [$ I] = $ arr_ B [$ I]) {
- Unset ($ arr_a [$ I], $ arr_ B [$ I]); // remove the same part
- } Else {
- If ($ I = 0)
- $ Flag = false; // There is no intersection between two paths
- Break; // stop the loop
- }
- }
- $ Str = $ flag? Str_repeat ('../', count ($ arr_ B) + 1): '/'; // if there is no intersection, it is the root directory "/" [In Linux, change it in windows]
- Return $ str. join ('/', $ arr_a); // concatenate and return
- }
- // TEST
- $ A = '/a/B/c/d/e. php ';
- $ B = '/a/B/12/34/c. php ';
- Echo 'path a: '. $;
- Echo'
PATH B: '. $ B;
- Echo'
The relative path of path a and PATH B (using c. php to access the e. php path) is :';
- Echo getRelativePath ($ a, $ B );
- // ----- OUTPUT ------------- =
- Path a:/a/B/c/d/e. php
- PATH B:/a/B/12/34/c. php
- The relative path of path a and PATH B (use c. php to access the e. php path) is:.../c/d
|