URL routing and regular expressions

If you know what exactly each segment of URL should mean, isn’t that will be easier to just split them?
Something like this (sample code, haven’t tested):

function getRoute($url){

    $url = trim($url, '/');
    $urlSegments = explode('/', $url);

    $scheme = ['area', 'controller', 'action', 'params'];
    $route = [];

    foreach ($urlSegments as $index => $segment){        
        if ($scheme[$index] == 'params'){
            $route['params'] = array_slice($urlSegments, $index);
            break;
        } else {
            $route[$scheme[$index]] = $segment;
        }
    }

    return $route;

}

then if you call

getRoute('/site/vm/view/1/2');

it should return

[
    'area' => 'site',
    'controller' => 'vm',
    'action' => 'view',
    'params' => [1, 2]
]

And I wouldn’t treat page number as something standalone. Basically, it can be passed as one of regular params.

1 Like