[ASP]過濾非BIG5編碼字元

這篇文章利用了之前的單字元判斷是否為 BIG5 的 ASP程式進行實作 (link), 由於是一個字一個字判定, 所以效率不會太好, 但可以快速解決有關在 UTF-8轉到 BIG5時, 不在該字元集的文字內容, 以過濾掉這類特殊的問題. 程式碼如下:

Function IsBig5(strChar) 
    ' check A440~C67E 常用字, C940~F9D5 次常用字 
    session.codepage="950"  
    Dim lngAsc  
    lngAsc = Asc(strChar)  
    IsBig5 = (lngAsc >= -23488 And lngAsc <= -14722)  
    If Not IsBig5 Then IsBig5 = (lngAsc >= -14016 And lngAsc <= -1579)  
    session.codepage="65001"  
End Function

Function TrimNonBig5(strUTF8)
    For i=1 to Len(strUTF8)  
        charTemp = Mid(strUTF8,i,1)  
        If IsBig5(charTemp) Then
            TrimNonBig5 = TrimNonBig5 + charTemp
        End If
    Next  
End Function

str1 = "桃之雫果凍"
response.write TrimNonBig5(str1)
' output 桃之果凍

str2 = "洋風和菓子零食"
response.write TrimNonBig5(str2)
' output 洋風和子零食

str3 = "游錫堃王建煊"
response.write TrimNonBig5(str3)
' output 游錫王建

以上的程式可以有效地將非在 Big5 字元集中的文字過濾, 避免與傳統編碼程式溝通時的問題.

[2014/11/10 11:12]
若是有需要再補上 ASCII 字元集區段的部分, 可以使用 ASC 於 32~126 的 ASCII Printable 即可(參考資料: http://en.wikipedia.org/wiki/ASCII#ASCII_printable_code_chart), 記得是在轉 code page前測試 ASCII, 程式碼如下:

Function IsBig5Asc(strChar)
    ' check A440~C67E 常用字, C940~F9D5 次常用字, asc printable 32~126
    Dim lngAsc
    lngAsc = Asc(strChar)
    IsBig5Asc = (lngAsc >= 32 And lngAsc <= 126)
    session.codepage="950"
    lngAsc = Asc(strChar)
    If Not IsBig5Asc Then IsBig5Asc = (lngAsc >= -23488 And lngAsc <= -14722)
    If Not IsBig5Asc Then IsBig5Asc = (lngAsc >= -14016 And lngAsc <= -1579)  
    session.codepage="65001"  
End Function

Function TrimNonBig5Asc(strUTF8)
    For i=1 to Len(strUTF8)  
        charTemp = Mid(strUTF8,i,1)  
        If IsBig5Asc(charTemp) Then
            TrimNonBig5Asc = TrimNonBig5Asc + charTemp
        End If
    Next  
End Function

str1 = "桃之雫果凍1200G(1.2公斤)"
response.write TrimNonBig5Asc(str1)
' output 桃之果凍1200G(1.2公斤)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *