简体   繁体   English

mod_rewrite将'_'替换为'-'

[英]mod_rewrite replace '_' with '-'

I'm almost there with a mod_rewrite rule, but I've caved in :) 我几乎有一个mod_rewrite规则,但是我已经陷入了:)

I need to rewrite 我需要重写

country/[countryname].php 

to

country/[countryname]/

however, [countryname] may have an underscore like this: 'south_africa.php' and if it does I want to replace it with a hypen: 'south-africa/' 但是,[countryname]可能带有这样的下划线:'south_africa.php',如果确实如此,我想将其替换为连字符:'south-africa /'

I also want to match if the country has numbers following it: 'france03.php' to 'france/' 我也想匹配该国家/地区后面是否有数字:“ france03.php”到“ france /”

Heres my rule, its almost there but its still adding a hyphen even if there is no second part after the underscore. 这是我的规则,几乎在这里,但是即使下划线后没有第二部分,它仍然会添加连字符。

RewriteRule ^country/(.*)_(.*?)[0-9]*\.php$ country/$1-$2 [R=301,L]

so currently 'country/south_.php' becomes 'country/south-/' 因此目前“ country / south_.php”变为“ country / south- /”

Can someone please help me find the missing piece of the puzzle? 有人可以帮我找到拼图的缺失部分吗? Thanks. 谢谢。

Try this: 尝试这个:

RewriteRule ^country/([^_]*)_([^_]*?)\d*\.php$ country/$1-$2 [R=301,L]

This rule will match urls with a single underscore - you'll need a different rule for more underscores or none. 此规则将使用单个下划线匹配url-您需要使用其他规则来获得更多的下划线,否则将没有。

If you want to make sure $2 contains only letter and isn't empty, change ([^_]*?) it to ([a-zA-Z]+) . 如果要确保$2仅包含字母并且不为空,请将([^_]*?)更改为([a-zA-Z]+)

Alternatively you could do it over several passes: 或者,您可以通过几遍操作来完成此操作:

# If request is for something in "country/"
RewriteCond %{REQUEST_URI} ^country/.+\.php$

# Replace underscore and digits with (single) hyphen
RewriteRule [_0-9]+ \-

# Remove extension (and possible trailing hyphen)
RewriteRule ^(.*)-?\.php$ $1

# Final rewrite
RewriteRule ^country/(.*)$ country/$1 [R=301,L]

Untested ... and not necessarily "pretty" :) 未经测试...不一定是“漂亮” :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM