提问人:Marco 提问时间:7/5/2023 最后编辑:RavinderSingh13Marco 更新时间:7/5/2023 访问量:56
正则表达式:将 2 条规则合并为 1 条
Regex: combine 2 rules into 1
问:
我有一个规则。我需要找到点(或不点)之后的第一个整数。下面是一个很好的良好数据示例,这些数据匹配并找到第一个捕获组:.htacces
discography/type
discography/type/
discography/type/4
discography/type/albums.4
下面是一个糟糕的数据示例:
discography/type/4//
discography/type//
discography/type/singles.4//
有效的规则:
RewriteRule ^discography\/type(?:\/(?:(?:[^\/]*[.])?(\d+)\/?|[^\/]+\/?)?)?$ discography/releases.php?type=$1 [L,QSA]
到目前为止,一切都很好:https://regex101.com/r/4BwJ7z/1
这是我需要帮助的地方。
我还有另一个规则,将几个关键字(,)匹配为第一个捕获组:ep
singles
discography/ep
discography/ep/
discography/singles
discography/singles/
RewriteRule ^discography\/(ep|singles)\/?$ discography/releases.php?type=$1 [L,QSA]
https://regex101.com/r/dGEDdx/1
我需要将这 2 条规则合并为 1 条。 有什么想法吗?
答:
3赞
RavinderSingh13
7/5/2023
#1
第1种解决方案:在单个规则中,两个规则的组合请尝试遵循 .htaccess 规则。这是正则表达式的在线演示。
RewritEngine ON
RewriteRule ^discography\/(?:(ep|singles)|type(?:\/?(?:(?:[^\/]*[.])?(\d+)\/?|[^\/]+\/?)?))\/?$ discography/releases.php?type=$1$2 [L,QSA,NC]
第二种解决方案:将这两个规则都保留到您的 .htaccess 规则文件中怎么样?我的意思是,一次只能通过规则,对吧?所以 1 美元应该只提供 1 个值。我还向它添加了标志以启用规则上的忽略大小写。NC
RewriteEngine ON
RewriteRule ^discography\/(ep|singles)\/?$ discography/releases.php?type=$1 [L,QSA,NC]
RewriteRule ^discography\/type(?:\/(?:(?:[^\/]*[.])?(\d+)\/?|[^\/]+\/?)?)?$ discography/releases.php?type=$1 [L,QSA,NC]
评论
ep|singles)\/?$|type(?:\/(?:(?:[^\/]*[.])?(\d+)\/?|[^\/]+\/?)?)?$) 唱片/发行.php?type=$1$2
。但我怀疑它是否比使用两个重写规则更好。$_GET
discography/type/