【问题标题】:Pretty URL change variable seporator漂亮的 URL 更改变量分隔符
【发布时间】:2017-05-06 15:50:23
【问题描述】:

我正在尝试通过一个漂亮的 url 传递变量,我可以使用以下方法来实现:

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"];

但是,我需要我的 URL 如下所示:

domain.com/exercises/lunge-with-dumbells

我可以使用

让它工作

exercises/?exercise=lunge-with-dumbells 和这个 PHP 函数:

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

但是,我想要一个漂亮的 URL,其中变量字符串由 - 分隔,而不是 +

非常感谢。

【问题讨论】:

    标签: php .htaccess friendly-url


    【解决方案1】:

    要让您的 .htaccess 匹配使用“-”分隔符而不是“+”分隔符美化的 url,您只需将管理重写规则的正则表达式更改为您的 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 2014-01-25
      • 2018-02-18
      • 1970-01-01
      • 2015-08-10
      相关资源
      最近更新 更多