APACHE mod_rewrite change variable name in query string

霸气de小男生 提交于 2020-01-05 09:02:29

问题


I'm trying to change a variable name in a query string, so it's usable by my PHP code.

The query gets posts from an external system, so I can't control that they are posting a variable name with a space in it. And that makes it impossible for me to use the PHP $_GET function.

I need to change variable%20name to ?new1

And I need to change variable2 to new2

There are many variables passed in the query, but only these two need to be changed. The rest can stay the same or even disappear.

So ?variable%20name=abc&variable2=xyz

Needs to end up as ?new1=abc&new2=xyz

Also, they may not be in this order and there may be more variables

So ?variable%20name=abc&blah=123&blah2=456&variable2=xyz

Could end up as ?new1=abc&new2=xyz

OR as ?new1=abc&blah=123&blah2=456&new2=xyz

Either way would be fine!

Please give me the mod_rewrite rule that will fix this.

Thank you in advance!


回答1:


Parsing the query string with mod_rewrite is a bit of a pain, has to be done with RewriteCond and using %n replacements in a subsequent RewriteRule, probably easier to manually break up the original query string in PHP.

The full query string can be found (within PHP) in $_SERVER['QUERY_STRING'].

You can split it up using preg_split() or explode(), first on &, then on =, to get key/value pairs.


Using custom%20cbid=123&blahblahblah&name=example as an example.

$params = array();
foreach (explode("&", $_SERVER['QUERY_STRING']) as $cKeyValue) {
    list ($cKey, $cValue) = explode('=', $cKeyValue, 2);
    $params[urldecode($cKey)] = urldecode($cValue);
}

// Would result in:

$params = array('custom cbid' => 123,
                'blahblahblah' => NULL,
                'name' => example);


来源:https://stackoverflow.com/questions/5451183/apache-mod-rewrite-change-variable-name-in-query-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!