htaccess file: replace spaces with hypen + link to new url

笑着哭i 提交于 2019-12-24 10:35:44

问题


I'd like to replace any space in my URLs with a hypen

This is my complete htaccess file:

Options -MultiViews

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

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

The problem is that my title often contains spaces so it returns this url:

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

Url that I'd like to create: example.com/archive/this-is-a-test

I read that I could include a "\" to remove any spaces, but my attempts didn't work...

A related question: how do I link to this new url from another webpage? I cannot use the following php cause that would just return the url with the "%20" symbols:

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

回答1:


place this in your htaccess file

RewriteEngine On

remove spaces from start or after with +

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

remove spaces from end or before with +

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

replace spaces by - in betweenwith +

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


来源:https://stackoverflow.com/questions/23956478/htaccess-file-replace-spaces-with-hypen-link-to-new-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!