Sunday, October 17, 2010

PHP transform absolute path into relative path (string difference)

The context
I needed to transform an absolute path, to a relative one.
IE: I had a
$path1 = "/var/www/classifieds/Includes/configs"
(this was the location of the php script that was executing), and a
$path2 = "/var/www/classifieds/images/my_images"
. From those two paths, I needed something
like $path3 = "images/my_images"
which could be translated into something like
"The difference between the two paths - the relative path, instead the absolute one"
.


The solution

Write a for loop that identifies the common characters of the two strings, and then str_replace them with "":

for ($i = 0, $common_path = "", $path1 = dirname(__FILE__) ; ($i < strlen($path1)) && ($path1[$i] == $path2[$i]); $common_path .= $path1[$i], $i++ ){ }

$new_val = str_replace($common_path, "", $path2);

Hope you liked it - if you have other nice to see code, you are welcome to post it here

0 comments:

Post a Comment