我正在尝试创建一个 .htaccess 来处理一些 PHP MVC 请求。标准格式为:
domain.com/module/Controller/action
但在某些情况下我需要传递 GET 变量,例如:
domain.com/module/Controller/action/foo/bar
我需要在 PHP 中接收 var foo
值为 bar
domain.com/module/Controller/action/foo/bar/hello/world
同样的事情,我需要获取 var foo
值为 bar
和hello
值为 world
对于未定义数量的变量,规则必须相同,如下所示。
domain.com/module/Controller/action/foo/bar/hello/world/[...]/last/var
我总是有成对的var
/value
在模块、 Controller 和操作之后。
我使用的RewriteRule如下,它仅检测模块、 Controller 和操作。
RewriteRule ^([a-z]+)/([A-Z]{1}[a-zA-Z]+)/([a-zA-Z]+)/?$ index.php?module=$1&controller=$2&action=$3
我不知道我应该如何改变才能获得预期的行为。非常欢迎任何帮助。
最佳答案
遵循以下规则
RewriteRule ^/?([a-z]+)/([A-Z][a-zA-Z]+)/([a-zA-Z]+)((:?/[^/]+/[^/]+)*)$ /index.php?module=$1&controller=$2&action=$3&rest=$4
将生成以下$_GET
数组
Array
(
[module] => module
[controller] => Controller
[action] => action
[rest] => /hello/world
)
您可以使用 PHP 爆炸方法和一些数组操作来解析 [rest]
此外,您不需要 [A-Z]{1}
,它已经匹配一个标记(标记或字符?),因此您可以将其替换为 [A-Z]
更新
如果您不想强制区分大小写的 URL,则可以使用以下简化规则。
RewriteRule ^/?([a-z]+)/([a-z]+)/([a-z]+)((:?/[^/]+/[^/]+)*)$ /index.php?module=$1&controller=$2&action=$3&rest=$4 [NC]
更新2
((:?/[^/]+/[^/]+)*)
是抓取/key/value
对可以分解为
/
匹配 /
[^/]+
匹配 1 个或多个非 /
的标记
(...)*
查找 (
和 )
之间的任何内容 0 次或尽可能多次。
:?
将 (...)
从捕获组转换为仅绑定(bind)组,并且不为其创建变量。
因此,实际上,所述部分尝试匹配 /anyting_that_is_not_slash/anything_that_is_not_slash
的出现,如果找到,则将整个内容放入 $4
关于php - 如何在自定义 MVC .htaccess 中传递多个获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23630983/