Night | Snow

Simplify a path/url in Php

Posted on: November 25th, 2009

Tags: , , ,

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.

function SimplifyPath($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

News

Martin Fischer said:

Client and partner of simra.ch

Wir können Simon Schärer als kompetenter und zuverlässiger Programmierer höchst weiterempfehlen. Er ist nicht nur ein guter Programmierer, sondern auch ein ausgezeichneter Designer.
Danke Developer’s Island

Follow us on Twitter

favorite

I get asked a lot - which SDK should we use for web programming? I recommend Netbeans

my toolbar

Simra GameMP3 playersubscribe to RSSMy delicious bookmarksFacebookTwitterE-mail

No Responses to “Simplify a path/url in Php”

RSS Feed Icon  Subscribe to comments follow-up

Trackbacks/Pingbacks

Leave a reply

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Latest Tweet

loading...