如何在网址中替换短划线( - )而不是空格?

时间:2016-05-11 06:48:37

标签: php .htaccess yii2

我正在使用Yii2,我正在尝试将网址空格更改为短划线( - )

我使用的浏览器默认情况下会在网址中添加加号(+)而不是空格;

例如这句话:

"如何替换破折号而不是空格"

更改为:

/mysite.com/how+to+replace+dash+instead+of+space

但我想把破折号( - )而不是加(+)像打击网址一样:

/mysite.com/how-to-replace-dash-instead-of-space

2 个答案:

答案 0 :(得分:1)

您可以在htaccess中使用以下规则:

RewriteEngine on

#1If uri has spaces, convert them to hyphens and set an  env "hasspaces"
RewriteRule (.*)\s(.*) $1-$2 [N,E=hasspaces:yes]
#2if the env "hasspaces" is set, we will redirect spaces to hyphens 
RewriteCond %{ENV:hasspaces} yes
RewriteRule ^(.+)$ /$1 [L,R]

这会将uri中的所有空格转换为连字符并重定向url

  • example.com/hello word

  • example.com/hello-word

答案 1 :(得分:0)

在执行此操作之前请确保因为-(破折号)在Yii2的网址路由约定中使用并与动作名称中的大写字母匹配

  

控制器类命名

     

可以从中派生控制器类名   控制器ID根据以下过程:

     

将每个单词中用连字符分隔的第一个字母翻到上面   案件。请注意,如果控制器ID包含斜杠,则仅限此规则   适用于ID中最后一个斜杠之后的部分。删除连字符和   用反斜杠替换任何正斜杠。附加后缀   控制器。添加控制器名称空间。以下是一些   假设控制器名称空间采用默认值   应用\控制器:

     

文章成为app \ controllers \ ArticleController;发表评论   成为app \ controllers \ PostCommentController;管理员/注释后   成为app \ controllers \ admin \ PostCommentController;   adminPanels / post-comment成为   应用\控制器\ adminPanels \ PostCommentController。控制器类   必须是可自动加载的。因此,在上面的例子中,   文章控制器类应保存在别名为的文件中   @应用程序/控制器/ ArticleController.php;管理员/后评论   控制器应该在   @应用程序/控制器/管理/ PostCommentController.php。

有关完整指南,请参阅此http://www.yiiframework.com/doc-2.0/guide-structure-controllers.htmlhttp://www.yiiframework.com/doc-2.0/guide-structure-controllers.html

相关问题