本文介绍了使用未知数量的变量进行 mod_rewrite的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 mod_rewrite 来处理未知数量的变量.

I'm trying to use mod_rewrite to handle an unknown number of variables.

示例网址为:

example.com/var1-var2-var3/title

example.com/var1-var2-var3/title

到目前为止我有这个:

RewriteRule ^([^/.]+)-([^/]*)(.*)$ $3?version[]=$1&version[]=$2 [QSA,N]
RewriteRule ^([^/.]+)/?$ ?title=$1 [QSA,N]
RewriteRule ^/?$ /index.php [QSA,L]

返回:数组([标题] => 标题[版本] => 数组([0] => var1-var2 [1] => var3))

This returns: Array ( [title] => title [version] => Array ( [0] => var1-var2 [1] => var3 ) )

我需要它返回:Array ( [title] => title [version] => Array ( [0] => var1 [1] => var2 [2] => var3 ) )

I need it to return: Array ( [title] => title [version] => Array ( [0] => var1 [1] => var2 [2] => var3 ) )

推荐答案

我认为您无法在单个 RewriteRule 正则表达式中捕获任意数量的参数.重定向到 index.php?version=var-var2-var3 然后在 PHP 中在 $_POST[' 上执行 explode() 不是更容易吗?版本']?

I don't think you can capture an arbitrary number of arguments in a single RewriteRule regex. Wouldn't it be easier to redirect to index.php?version=var-var2-var3 then in PHP do an explode() on $_POST['version']?

您可以为有限数量的变量(我相信 9 是捕获的最大子组)执行此操作,然后删除多余的空条目.在我看来,Messier 然后是简单的 expand() 替代方案,但在这里:

You can do it for a bounded number of vars (9 is the maximum captured subgroups I believe) and then remove redundant empty entries. Messier then the simple explode() alternative in my opinion, but here you go:

# Convert up to 8 arguments.
RewriteRule ^/([^-]+)-(?:([^-]+)-)?(?:([^-]+)-)?(?:([^-]+)-)?(?:([^-]+)-)?(?:([^-]+)-)?(?:([^-]+)-)?(?:([^-]+)-)?/(.*)$ index.php?t=$9&v[]=$1&v[]=$2&v[]=$3&v[]=$4&v[]=$5&v[]=$6&v[]=$7&v[]=$8
# Strip empty ones.
RewriteRule [?&]v[]=$ "" [N]

您还可以通过在重写引擎的每次运行中将一个 var 移动到新格式并继续运行它直到用完 var 来执行复杂的循环,但我认为这不仅仅是 URL 重写引擎应该负责

You can also do a complicated loop by moving one var to the new format on each run of the rewriting engine and go on running it until you run out of vars, but I think that's more than a URL rewriting engine should be responsible for.

编辑 2: 好的,这是我提到的循环:

EDIT 2: Ok, here's the loop I mentioned:

RewriteEngine on
RewriteRule ^(.*)/([^/]+)$ $1&page=$2 [L]
RewriteRule ^([^-]+)-(.*)?$ $2&v[]=$1 [L]
RewriteRule ^(?!index.php)([^-]+)$ /index.php?v[]=$1 [L]

它转换了一个示例 URL,如下所示:

It transform a sample URL as follows:

var1-var2-var3/title                             <-- Original
var1-var2-var3&page=title
var2-var3&page=title&v[]=var1
var3&page=title&v[]=var1&v[]=var2
index.php?v[]=var3&page=title&v[]=var1&v[]=var2  <-- Final

这篇关于使用未知数量的变量进行 mod_rewrite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 02:27