Coldfusion - Remove all non-numeric values from a list?
I have a list of IDs being passed through the URL. I want to do some sanitizing before running a query based on thos开发者_StackOverflowe IDs. I have this:
<cfset URL.ID = ReReplaceNoCase(URL.ID,"[^0-9]","","ALL")>
But I realize that's stripping the comma out also. Is there a simple way to remove non numeric values from a list in Coldfusion?
Why not just add a comma to your regex?
<cfset URL.ID = ReReplaceNoCase(URL.ID,"[^0-9]","","ALL")>
becomes
<cfset URL.ID = ReReplaceNoCase(URL.ID,"[^0-9,]","","ALL")>
<cfscript>
//Test Case
URL.ID= "abc,12,3,zoiui fdsoaiu ,323333";
//URL.ID= "12,3,323333"
URL.ID= reReplace( URL.ID , "([^0-9,]+,)" , "" , "all" );
</cfscript>
That being said, you'd want to put this in a <cfqueryparam .. list= "true" />
Regex still leaves extra commas in the string and accepts partial numbers, instead I'd use a loop with integer validation:
<cfset url.id = "100,abc,102z,eee,22.5,773">
<!--- 100,,102,,225,773 --->
<cfoutput>#ReReplaceNoCase(URL.ID,"[^0-9,]","","ALL")#<br /></cfoutput>
<cfset dirtyIds = listToArray(url.id)>
<cfset cleanIds = []>
<cfloop array="#dirtyIds#" index="dirtyId">
<cfif isValid("integer",dirtyId)><cfset arrayAppend(cleanIds, dirtyId)></cfif>
</cfloop>
<cfset url.id = arrayToList(cleanIds)>
<!--- 100, 773 --->
<cfoutput>#url.id#</cfoutput>
@orangepips
isNumeric() should work as well.
<cfset url.id = "100,abc,102z,eee,22.5,773">
<cfset variables.newlist = ''>
<cfloop list="#url.id#" index="i">
<cfif isNumeric(i)>
<cfset variables.newlist = ListAppend(variables.newlist,i)>
</cfif>
</cfloop>
<cfoutput>#variables.newlist#</cfoutput>
精彩评论