Welcome Guest, Not a member yet? Register   Sign In
[Helper] Automatically link to routes in site_url(), redirect() and anchor()
#5

[eluser]zentair[/eluser]
I've made some improvements and modifications to this function:
1) Get the routes via $CI->router->routes
2) Match everything between parentheses
3) used preg_split and simply swap the even numbered matches
4) break after finding a match, this is required because in the Router higher routes will always take precedence over lower ones (http://ellislab.com/codeigniter/user-gui...uting.html).
5) I also added the functionality in http://ellislab.com/forums/viewthread/167695/

This works fine for routes like:
Code:
$route['view/(:any)/(:num)'] = 'entries/view/$1/$2';  
$route['admin/auth(.*)'] = 'auth$1';

It does not work for routes that use expressions without parentheses
Code:
$route['product/:num'] = "catalog/product_lookup";
fortunately I've never wanted to use such a route.

Code:
function site_url($uri = '')
{
    $CI = get_instance();
    if     (func_num_args() > 1) $uri = implode('/', func_get_args());
    elseif (is_array($uri))      $uri = implode('/', $uri);
    
    if (in_array($uri, $CI->router->routes))
    {
       $uri = array_search($uri, $CI->router->routes);
    }    
    else foreach ($CI->router->routes as $route => $replace)
    {
        $route   = preg_split('/(\(.+?\))/', $route,-1,PREG_SPLIT_DELIM_CAPTURE);
        $replace = preg_split('/(\$\d+)/', $replace,-1,PREG_SPLIT_DELIM_CAPTURE);
        if (count($route) != count($replace)) continue;

        $newroute = $newreplace = '';
        for ($i=0; $i < count($route); $i++)
            if ($i % 2)
            {
                $newroute .= $replace[$i];
                $newreplace .= $route[$i];
            }
            else
            {
                $newroute .= $route[$i];
                $newreplace .= $replace[$i];
            }
        $newreplace = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $newreplace));
        
        if (preg_match("#^$newreplace\$#", $uri))
        {
            $uri = preg_replace("#^$newreplace\$#", $newroute, $uri);
            break;
        }
    }
    return $CI->config->site_url($uri);
}

Update: After discovering my site_url() calls were rewritten but form_open() wasn't I think it's better to add this functionality to the config class after all, config->site_url() is used by more helpers and libraries.


Messages In This Thread
[Helper] Automatically link to routes in site_url(), redirect() and anchor() - by El Forum - 08-07-2011, 07:55 AM



Theme © iAndrew 2016 - Forum software by © MyBB