Codeigniter Routes regex - using dashes in controller/method names Codeigniter Routes regex - using dashes in controller/method names codeigniter codeigniter

Codeigniter Routes regex - using dashes in controller/method names


That is exactly my requirement too and I was using routes like

$route['logued/presse-access'] = "logued/presse_access";

In my previous project I needed to create 300-400 routing rules, most of them are due to dash to underscore conversion.

For my next project I eagerly want to avoid it. I have done some quick hack and tested it, though have not used in any live server, its working for me. Do the following..

Make sure the subclass_prefix is as follows in your system/application/config/config.php

$config['subclass_prefix'] = 'MY_';

Then upload a file named MY_Router.php in system/application/libraries directory.

<?phpclass MY_Router extends CI_Router {     function set_class($class)     {        //$this->class = $class;        $this->class = str_replace('-', '_', $class);        //echo 'class:'.$this->class;    }    function set_method($method)     {//      $this->method = $method;        $this->method = str_replace('-', '_', $method);    }    function _validate_request($segments)    {        // Does the requested controller exist in the root folder?        if (file_exists(APPPATH.'controllers/'.str_replace('-', '_', $segments[0]).EXT))        {            return $segments;        }        // Is the controller in a sub-folder?        if (is_dir(APPPATH.'controllers/'.$segments[0]))        {                   // Set the directory and remove it from the segment array            $this->set_directory($segments[0]);            $segments = array_slice($segments, 1);            if (count($segments) > 0)            {                // Does the requested controller exist in the sub-folder?                if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().str_replace('-', '_', $segments[0]).EXT))                {                    show_404($this->fetch_directory().$segments[0]);                }            }            else            {                $this->set_class($this->default_controller);                $this->set_method('index');                // Does the default controller exist in the sub-folder?                if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))                {                    $this->directory = '';                    return array();                }            }            return $segments;        }        // Can't find the requested controller...        show_404($segments[0]);    }}

Now you can freely use url like http://example.com/logued/presse-access and it will call the proper controller and function by automatically converting dash to underscore.

Edit:Here is our Codeigniter 2 solution which overrides the new CI_Router functions:

<?phpclass MY_Router extends CI_Router {     function set_class($class)     {        $this->class = str_replace('-', '_', $class);    }    function set_method($method)     {        $this->method = str_replace('-', '_', $method);    }    function set_directory($dir) {        $this->directory = $dir.'/';    }    function _validate_request($segments)    {        if (count($segments) == 0)        {            return $segments;        }        // Does the requested controller exist in the root folder?        if (file_exists(APPPATH.'controllers/'.str_replace('-', '_', $segments[0]).'.php'))        {            return $segments;        }        // Is the controller in a sub-folder?        if (is_dir(APPPATH.'controllers/'.$segments[0]))        {            // Set the directory and remove it from the segment array            $this->set_directory($segments[0]);            $segments = array_slice($segments, 1);            while(count($segments) > 0 && is_dir(APPPATH.'controllers/'.$this->directory.$segments[0]))            {                // Set the directory and remove it from the segment array                $this->set_directory($this->directory . $segments[0]);                $segments = array_slice($segments, 1);            }            if (count($segments) > 0)            {                // Does the requested controller exist in the sub-folder?                if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().str_replace('-', '_', $segments[0]).'.php'))                {                    if ( ! empty($this->routes['404_override']))                    {                        $x = explode('/', $this->routes['404_override']);                        $this->set_directory('');                        $this->set_class($x[0]);                        $this->set_method(isset($x[1]) ? $x[1] : 'index');                        return $x;                    }                    else                    {                        show_404($this->fetch_directory().$segments[0]);                    }                }            }            else            {                // Is the method being specified in the route?                if (strpos($this->default_controller, '/') !== FALSE)                {                    $x = explode('/', $this->default_controller);                    $this->set_class($x[0]);                    $this->set_method($x[1]);                }                else                {                    $this->set_class($this->default_controller);                    $this->set_method('index');                }                // Does the default controller exist in the sub-folder?                if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.'.php'))                {                    $this->directory = '';                    return array();                }            }            return $segments;        }        // If we've gotten this far it means that the URI does not correlate to a valid        // controller class.  We will now see if there is an override        if ( ! empty($this->routes['404_override']))        {            $x = explode('/', $this->routes['404_override']);            $this->set_class($x[0]);            $this->set_method(isset($x[1]) ? $x[1] : 'index');            return $x;        }        // Nothing else to do at this point but show a 404        show_404($segments[0]);    }}

Now one has to place this file like application/core/MY_Router.php and make sure he has subclass_prefix is defined as $config['subclass_prefix'] = 'MY_'; in application/config/config.php

Few extra lines of code has been added in method _validate_request():

while(count($segments) > 0 && is_dir(APPPATH.'controllers/'.$this->directory.$segments[0])){    // Set the directory and remove it from the segment array    $this->set_directory($this->directory . $segments[0]);    $segments = array_slice($segments, 1);}

It is used so that one can make use of multi-level subdirectory inside controllers directory, whereas normally we can use single level subdirectory inside controllers folder and can call it in url. One can remove this code if it not necessary but it has no harm on the normal flow.


Just coming back to this question after upgrading to CodeIgniter 2. Here is a solution which is more robust than the accepted answer because it will survive CodeIgniter core updates.

<?phpclass MY_Router extends CI_Router{     public function set_class($class)     {        parent::set_class($this->_repl($class));    }    public function set_method($method)     {        parent::set_method($this->_repl($method));    }    public function _validate_request($segments)    {        if (isset($segments[0]))            $segments[0] = $this->_repl($segments[0]);        if (isset($segments[1]))            $segments[1] = $this->_repl($segments[1]);        return parent::_validate_request($segments);    }    private function _repl($s)    {        return str_replace('-', '_', $s);    }}

It should be saved as application/core/MY_Router.php. Now, you can have Controller and Method names with underscores in them such as Abc_Def (in file abc_def.php) and refer to them with the URL /abc-def.


Actually this is native now in Codeigniter 3Just do this in routes file

   $route['translate_uri_dashes'] = TRUE;

And it will do it for controllers and methods automatically .
Please vote this answer up , as it's most recent