Simplify a path/url in Php
Posted on: November 25th, 2009
Here’s a little Php function that simplifies dirs like/./dir ordir/../../dir/ and returns a canonicalized pathname. Unlike the function realpath() it works with every path and url and doesn’t return the absolute path.
$dirs = explode('/',$path);
for($i=0; $i<count($dirs);$i++) {
if($dirs[$i]=="." || $dirs[$i]=="") {
array_splice($dirs,$i,1);
$i--;
}
if($dirs[$i]=="..") {
$c = count($dirs);
$dirs=Simplify($dirs, $i);
$i-= $c-count($dirs);
}
}
return implode('/',$dirs);
}
function Simplify($dirs, $idx) {
if($idx==0) return $dirs;
if($dirs[$idx-1]=="..") Simplify($dirs, $idx-1);
else array_splice($dirs,$idx-1,2);
return $dirs;
}
Posted in Php | Trackback Url








No Responses to “Simplify a path/url in Php”
Trackbacks/Pingbacks
Leave a reply