如何替换 URL"通过“-"还是“_"? [英] How to replace URL " " by "-" or "_"?
问题描述
在YII如果标题中有用于 url 的空格,则默认情况下空格将替换为+"号.像这样:
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
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
www.domain.com/event/view/id/Dj-Robag-Ruhme
或
www.domain.com/event/view/id/Dj_Robag_Ruhme
www.domain.com/event/view/id/Dj_Robag_Ruhme
现在我的 urlManager 是:
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>',
),
),
推荐答案
嗯,没什么奇怪的,因为 Yii 使用 urlencode
对 url 参数进行编码.
Well, nothing strange since Yii use urlencode
to encode url parameters.
第一种方法
你可以在你的模型中处理这个,例如:
You could handle this in your model, e.g. :
public function getUrl()
{
return Yii::app()->createUrl('/model/view', array(
'id'=>str_replace(' ', '-', $this->id),
));
}
不要忘记:
- 将
model
替换为您的模型名称, - 使用此方法获取您的模型网址,
在控制器中修改视图操作:
- 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);
// .....
}
第二种方法
您可以使用自己的 CUrlRule
类:
You could use your own CUrlRule
class :
http://www.yiiframework.com/doc/guide/1.1/en/topics.url#using-custom-url-rule-classes
这篇关于如何替换 URL"通过“-"还是“_"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!