Page 1 of 1

A Friendly URL parsing function posted for review/reuse

Posted: Tue Dec 09, 2008 3:32 pm
by Peter Anselmo
Hey All, I just spent a couple hours writing some code I thought I would pass on. I'm using a front-controller pattern to load in pages as called, and I needed a function to parse a friendly URL. My URLs are set up like so

http://www.mysite.com/page/key1/val1/key2/val2/

and it had to also work with folders

http://www.mysite.com/folder/page/key1/val1/key2/val2/

I searched around for a bit, and didn't find anything quite like I wanted. I also wanted it to fill the GET array like a normal, so the rest of the scripts wouldn't care how the URL was formed.

Code: Select all

function ParseFriendlyURL( $friendlyURL = $_SERVER['REQUEST_URI'] ) {
 
    //divide the URL into parts to make modification easier
    $splits = explode('/',trim($friendlyURL, '/'));
 
    //if no page is specified, default to index
    //otherwise, remove it from the array
    $page = !empty($splits) ? array_shift( $splits ) : 'index';
    
    //check if we're specifying directories
    //if so update the page string to reflect the heirarchy
    while( is_dir( $page ) ) {
        if( empty( $splits ) ) {
            $page .= '/index';
        } else {
            $page .= '/' . array_shift( $splits );
        }
    }
    
    //if we have additional parameters, place them into the _GET array
    while( !empty( $splits ) ) {
         $_GET[array_shift($splits)] = array_shift($splits);
    }
 
    return $page;
}
I'm using this and it works, but let me know if you see anything sloppy that could be improved :-)

Re: A Friendly URL parsing function posted for review/reuse

Posted: Tue Dec 09, 2008 4:05 pm
by dude81
Use regular expressions for url parsing. You need not so many while loops

Re: A Friendly URL parsing function posted for review/reuse

Posted: Tue Dec 09, 2008 4:22 pm
by Peter Anselmo
Dude,
Thanks for the feedback. At most I could see a regular expression replacing only the second while loop. As the syntax is the same for folders and variables, I would think the directory check loop is necessary outside of regex.