CF Quick Tip: Removing Non-Numeric Characters from a string

Suppose for a moment that you have a variable that you want to ensure it only contains numeric data. For instance a telephone, PIN, or credit card number.

ColdFusion makes this extremely simple to using a regular expression with the reReplace and reReplaceNoCase functions, as I will demonstrate below. For those new to ColdFusion the "re" in reReplace and reReplaceNoCase stands for "regular expression."

<cfset variables.myDirtyPhoneNbr = '(555) 222-4444'>
<cfset variables.myCleanPhoneNbr = reReplaceNoCase(variables.myDirtyPhoneNbr, '[^[:digit:]]', '', 'ALL')>

<!--- Now let's display the cleaned phone number --->
<cfoutput>#variables.myCleanPhoneNbr#</cfoutput>
<!--- myCleanPhoneNbr should now be: 5552224444 --->

With a few exceptions, ColdFusion supports Perl compliant Regular Expressions. For more information, check out the online documents at: http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=regexp_13.html

You can test out the removal of all none digits at the link below: Remove Non-Digit Character Example.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.