Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
 
 
 
500MB 27GB Web Hosting - $9.95/Month
 
 
 
 
 
Old Pages
 
Old Index
Site Map
What's New
 
Books
How To
Tips & Tricks
Tutorials
Stories
Performance
Essays
Links
Q & A
New in VB6
Free Stuff
Pictures
 
 
 
TitleURL encode a string
KeywordsURL, encode, code, string
CategoriesStrings, Utilities
 
Function URLEncode examines each character in a string. If the character is a space, it replaces it with a +. If the character is safe (as determined by the m_SafeChar array), the routine adds it to the result string. If the character is not safe, the routine replaces it with its hex value in the form %xx.

For example, this string:

    Some test (text) with wierd ;-) characters + more!

becomes this:

    Some+test+%28text%29+with+wierd+%3B%2D%29+characters+%2B+more%21
 
' Return a URL safe encoding of txt.
Private Function URLEncode(ByVal txt As String) As String
Dim i As Integer
Dim ch As String
Dim ch_asc As Integer
Dim result As String

    SetSafeChars

    result = ""
    For i = 1 To Len(txt)
        ' Translate the next character.
        ch = Mid$(txt, i, 1)
        ch_asc = Asc(ch)
        If ch_asc = vbKeySpace Then
            ' Use a plus.
            result = result & "+"
        ElseIf m_SafeChar(ch_asc) Then
            ' Use the character.
            result = result & ch
        Else
            ' Convert the character to hex.
            result = result & "%" & Right$("0" & _
                Hex$(ch_asc), 2)
        End If
    Next i

    URLEncode = result
End Function

Private m_SafeChar(0 To 255) As Boolean
' Set m_SafeChar(i) = True for characters that
' do not need protection.
Private Sub SetSafeChars()
Static done_before As Boolean
Dim i As Integer

    If done_before Then Exit Sub
    done_before = True

    For i = 0 To 47
        m_SafeChar(i) = False
    Next i
    For i = 48 To 57
        m_SafeChar(i) = True
    Next i
    For i = 58 To 64
        m_SafeChar(i) = False
    Next i
    For i = 65 To 90
        m_SafeChar(i) = True
    Next i
    For i = 91 To 96
        m_SafeChar(i) = False
    Next i
    For i = 97 To 122
        m_SafeChar(i) = True
    Next i
    For i = 123 To 255
        m_SafeChar(i) = False
    Next i
End Sub
 
 
Copyright © 1997-2003 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated