Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace URL " " by "-" or "_"?

In YII If there is blank space in title which is being used for url, then by default blank spaces are replaced by "+" sign. Something like this:

www.domain.com/event/view/id/Dj+Robag+Ruhme

What I want to do is, I want to replace "+" sign by "-" (dash sign) or by "_" (underscore). Something like this:

www.domain.com/event/view/id/Dj-Robag-Ruhme

or

www.domain.com/event/view/id/Dj_Robag_Ruhme

Right now my urlManager is:

'urlManager'=>array(
    'urlFormat'=>'path',
    'showScriptName'=>false,
    'caseSensitive'=>false,
    'rules'=>array(
        //'<controller:\w+>/<id:\d+>'=>'<controller>/view',
        //'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
        //'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
        ),
),
like image 542
Mohit Bhansali Avatar asked Mar 24 '23 05:03

Mohit Bhansali


1 Answers

Well, nothing strange since Yii use urlencode to encode url parameters.

First approach

You could handle this in your model, e.g. :

public function getUrl()
{
  return Yii::app()->createUrl('/model/view', array(
    'id'=>str_replace(' ', '-', $this->id),
  ));
}

Don't forget to :

  • replace model with the name of your model,
  • use this method to get your model url,
  • modify your view action in your controller :

    public actionView($id)
    {
        $id = str_replace('-', ' ', $id);
        // .....
    }
    

Second approach

You could use your own CUrlRule class :

http://www.yiiframework.com/doc/guide/1.1/en/topics.url#using-custom-url-rule-classes

like image 125
soju Avatar answered Apr 01 '23 06:04

soju