【问题标题】:htaccess file: replace spaces with hypen + link to new urlhtaccess 文件:用连字符替换空格+指向新网址的链接
【发布时间】:2014-05-30 14:03:19
【问题描述】:

我想用连字符替换网址中的任何空格

这是我完整的 htaccess 文件:

Options -MultiViews

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

RewriteRule ^archive/([^/]+)$ news?title=$1

问题是我的标题经常包含空格所以它返回这个网址:

example.com/archive/this%20is%20a%20test

我要创建的网址:example.com/archive/this-is-a-test

我读到我可以包含一个“\”来删除任何空格,但我的尝试没有奏效......

一个相关问题:如何从另一个网页链接到这个新网址?我不能使用以下 php 原因,它只会返回带有“%20”符号的 url:

<a class="readmore" href="/archive/<?php echo $row['title'];?>

【问题讨论】:

  • 网址中的空格无论如何都应该是+,而不是%20
  • 当您加载example.com/archive/this-is-a-test 时,它是否会为您正确加载页面。

标签: php .htaccess rewrite space hyphen


【解决方案1】:

把它放在你的 htaccess 文件中

RewriteEngine On

用 + 删除开头或之后的空格

RewriteRule ^(.*/|)[\s+]+(.+)$ $1$2 [L]

用 + 删除末尾或之前的空格

RewriteRule ^(.+?)[\s+]+(/.*|)$ $1$2 [L]

将空格替换为 - 和 +

RewriteRule ^([^\s+]*)(?:\s|+)+(.*)$ $1-$2 [L,R]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    相关资源
    最近更新 更多