你不需要正则表达式。事实上,有人已经为此构建了一个 UDF。
查询字符串删除变量
例子:
<cfset currentURL = CGI.SERVER_NAME & CGI.PATH_INFO & queryStringDeleteVar("productid,recordindex")>
UDF 代码:
<cfscript>
/**
* Deletes a var from a query string.
* Idea for multiple args from Michael Stephenson (michael.stephenson@adtran.com)
*
* @param variable A variable, or a list of variables, to delete from the query string.
* @param qs Query string to modify. Defaults to CGI.QUERY_STRING.
* @return Returns a string.
* @author Nathan Dintenfass (michael.stephenson@adtran.comnathan@changemedia.com)
* @version 1.1, February 24, 2002
*/
function queryStringDeleteVar(variable){
//var to hold the final string
var string = "";
//vars for use in the loop, so we don't have to evaluate lists and arrays more than once
var ii = 1;
var thisVar = "";
var thisIndex = "";
var array = "";
//if there is a second argument, use that as the query string, otherwise default to cgi.query_string
var qs = cgi.query_string;
if(arrayLen(arguments) GT 1)
qs = arguments[2];
//put the query string into an array for easier looping
array = listToArray(qs,"&");
//now, loop over the array and rebuild the string
for(ii = 1; ii lte arrayLen(array); ii = ii + 1){
thisIndex = array[ii];
thisVar = listFirst(thisIndex,"=");
//if this is the var, edit it to the value, otherwise, just append
if(not listFind(variable,thisVar))
string = listAppend(string,thisIndex,"&");
}
//return the string
return string;
}
</cfscript>
虽然,由于您要替换 URL 参数值,但QueryStringChangeVar可能更符合您的要求。
<cfscript>
/**
* Changes a var in a query string.
*
* @param name The name of the name/value pair you want to modify. (Required)
* @param value The new value for the name/value pair you want to modify. (Required)
* @param qs Query string to modify. Defaults to CGI.QUERY_STRING. (Optional)
* @return Returns a string.
* @author Nathan Dintenfass (nathan@changemedia.com)
* @version 2, September 5, 2002
*/
function QueryStringChangeVar(variable,value){
//var to hold the final string
var string = "";
//vars for use in the loop, so we don't have to evaluate lists and arrays more than once
var ii = 1;
var thisVar = "";
var thisIndex = "";
var array = "";
var changedIt = 0;
//if there is a third argument, use that as the query string, otherwise default to cgi.query_string
var qs = cgi.query_string;
if(arrayLen(arguments) GT 2)
qs = arguments[3];
//put the query string into an array for easier looping
array = listToArray(qs,"&");
//now, loop over the array and rebuild the string
for(ii = 1; ii lte arrayLen(array); ii = ii + 1){
thisIndex = array[ii];
thisVar = listFirst(thisIndex,"=");
//if this is the var, edit it to the value, otherwise, just append
if(thisVar is variable){
string = listAppend(string,thisVar & "=" & value,"&");
changedIt = 1;
}
else{
string = listAppend(string,thisIndex,"&");
}
}
//if it was not changed, add it!
if(NOT changedIt)
string = listAppend(string,variable & "=" & value,"&");
//return the string
return string;
}
</cfscript>