Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I have a user-entered string which I am using as a search term. I would like to display the results in a table named "SearchResults_"+SearchString. However the string could feasibly contain characters that can't be used for table names - spaces would be the most common and there are plenty of other strange characters in place names.

I would like to strip all special, non-alphanumeric characters from a string.

As far as I can see there aren't any built-in functions that would achieve this.

I can loop through the characters easily enough but comparing each one to a white-list is proving harder than I expected. I could do it with a epic if/else statement but that's just dirty! VB.net has IsLetterOrDigit() which would be nice. PHP has ctype_alnum(). In Python I'd just check it against a white-list string.

Any ideas?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Well that wasn't so hard.

Declare Sub Main
Declare Function RemoveSpecialChars(byval str as string) as String

Sub Main
    Dim t as string
    t = "this is a string with spaces and ' ! * & ^ % $ £ punctuation"

    Print Chr$(12) + "Original String: " + t
    Print "Tidy string: " + RemoveSpecialChars(t)

    End Program
End Sub

Function RemoveSpecialChars(byval str as string) as String
    Dim chr, out, nicechars as String
    Dim i, l as Integer

    nicechars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    l = Len(str)

    For i = 1 to l
        chr = Mid$(str, i, 1)
        If InStr(1, nicechars, chr) > 0 Then
            out = out + chr
        End If
    Next

    RemoveSpecialChars = out
End Function
share|improve this answer
    
+1 nice solution –  kinkajou Sep 2 '11 at 3:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.