How to replace URL “ ” by “-” or “_”?

青春壹個敷衍的年華 提交于 2019-12-06 04:04:17

问题


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>',
        ),
),

回答1:


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



来源:https://stackoverflow.com/questions/16186620/how-to-replace-url-by-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!