2016-12-21 51 views
1

我试图通过一个漂亮的url的变量,我可以achive使用下列内容:漂亮的URL变化而变化seporator

domain.com/exercises/lunge+with+dumbells

而这在我的.htaccess文件:

RewriteEngine On 
RewriteRule ^([a-zA-Z0-9+]+)$ index.php?exercise=$1 
RewriteRule ^([a-zA-Z0-9+]+)/$ index.php?exercise=$1 

哪使用php访问:

$urlVars = $_GET["exercise"];

不过,我需要我的网址阅读这样的:

domain.com/exercises/lunge-with-dumbells

我能得到这个使用

exercises/?exercise=lunge-with-dumbells这PHP函数工作:

$urlVars = $_GET["exercise"]; 
$newString = str_replace("-", " ", $urlVars); 

不过,我想就像一个漂亮的URL,其变量字符串由-分隔,而不是+

非常感谢。

回答

2

为了让您的.htaccess匹配了“-”分隔符,而不是“+”分隔符,你只需要改变管理重写规则,以你的PHP文件中的正则表达式的美化网址:

更改从规则:

RewriteEngine On 
RewriteRule ^([a-zA-Z0-9+]+)$ index.php?exercise=$1 
RewriteRule ^([a-zA-Z0-9+]+)/$ index.php?exercise=$1 

到:

RewriteEngine On 
RewriteRule ^([a-zA-Z0-9-]+)$ index.php?exercise=$1 
RewriteRule ^([a-zA-Z0-9-]+)/$ index.php?exercise=$1 

分裂正则表达式,在它的简单的组成部分,我们将创建一个说

^// match the beginning of a strings that start with 
    ( 
    [ // a pattern consisting of 
    a-z //a lowercase alphabet letter 
    A-Z //a uppercase alphabet letter 
    0-9 //a digit 
    - //and the minus sign (here we changed from the + sign to the new value) 
    ] 
    + //one or more occurence of the combination described above 
    ) 

有关正则表达式和的.htaccess请参考更多详细信息:https://httpd.apache.org/docs/current/rewrite/intro.html