htaccess file: replace spaces with hypen + link to

2019-08-03 09:38发布

问题:

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]