Saturday, June 17, 2006

Strip ALL unwanted characters from string in one line - CHRTRANEXCEPT()

Doing mostly VFP/WebConnect web applications means I do not have the nice 'picture' and 'format' properties that are available in the desktop VFP development environment.
A frequent requirement is stripping unallowed characters from an input field. Now, CHRTRAN is a great way to do this kind of thing - except that to use it you would have to figure out any and every character the user might have entered, and include all possibilities in a very long string. What we really need is a CHRTRANEXCEPT() function.

Several years ago I came up with this little meta-diddy for stripping all non-numeric characters from an entry field - so I can save a clean number withouy dollar signs or commas that a user might enter in my web forms. In this example I am assigning the asking price of a widgit to the variable m.Asking, and stripping it of all non-numeric info:
m.Asking = VAL(chrtran(m.Asking,chrtran(m.Asking,'0123456789.',''),''))
The inner chrtran extracts any nonallowed characters from the value (if any) and uses that string as the search string for the OUTER chrtran.

So, if we start with 123XYZ!*^, the inner chrtran will result in “XYZ!*^”, resulting in the final string 123.

This is also a cool way of removing ANY unallowed characters by simply specifying the allowed characters.

Very handy.

Links to this post:

<< Home