Research on small relative paths

Source: Internet
Author: User
Research on small relative paths
For example, find the relative path of the two paths and make a brick!

  1. /**
  2. * Find the relative path of the two paths
  3. * @ Param string $ patha path
  4. * @ Param string $ pathb path B
  5. * @ Author Joychao
  6. * @ Link http://www.joychao.cc
  7. * @ Return string relative path
  8. */
  9. Function getRelativePath ($ patha, $ pathb ){
  10. $ Arr_a = explode ('/', trim (dirname ($ patha ),'/'));
  11. $ Arr_ B = explode ('/', trim (dirname ($ pathb ),'/'));
  12. $ N = min (count ($ arr_a), count ($ arr_ B); // use the shortest path to loop
  13. $ Flag = true; // tag bit [whether the tag has no intersection at all]
  14. For ($ I = 0; $ I <$ n; $ I ++ ){
  15. If ($ arr_a [$ I] = $ arr_ B [$ I]) {
  16. Unset ($ arr_a [$ I], $ arr_ B [$ I]); // remove the same part
  17. } Else {
  18. If ($ I = 0)
  19. $ Flag = false; // There is no intersection between two paths
  20. Break; // stop the loop
  21. }
  22. }
  23. $ Str = $ flag? Str_repeat ('../', count ($ arr_ B) + 1): '/'; // if there is no intersection, it is the root directory "/" [In Linux, change it in windows]
  24. Return $ str. join ('/', $ arr_a); // concatenate and return
  25. }
  26. // TEST
  27. $ A = '/a/B/c/d/e. php ';
  28. $ B = '/a/B/12/34/c. php ';
  29. Echo 'path a: '. $;
  30. Echo'
    PATH B: '. $ B;
  31. Echo'
    The relative path of path a and PATH B (using c. php to access the e. php path) is :';
  32. Echo getRelativePath ($ a, $ B );
  33. // ----- OUTPUT ------------- =
  34. Path a:/a/B/c/d/e. php
  35. PATH B:/a/B/12/34/c. php
  36. The relative path of path a and PATH B (use c. php to access the e. php path) is:.../c/d

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.