我需要过滤掉像 /?-^%{}[];$=*`#|&@'\"<>()+,\ 这样的字符。如果它在查询中,我需要用空字符串替换它字符串。请帮帮我。我在 ASP 页面中使用它。
问问题
1959 次
3 回答
2
最好的想法是使用以下功能:
Public Function MakeSQLSafe(ByVal sql As String) As String
'first i'd avoid putting quote chars in as they might be valid? just double them up.
Dim strIllegalChars As String = "/?-^%{}[];$=*`#|&@\<>()+,\"
'replace single quotes with double so they don't cause escape character
If sql.Contains("'") Then
sql = sql.Replace("'", "''")
End If
'need to double up double quotes from what I remember to get them through
If sql.Contains("""") Then
sql = sql.Replace("""", """""")
End If
'remove illegal chars
For Each c As Char In strIllegalChars
If sql.Contains(c.ToString) Then
sql = sql.Replace(c.ToString, "")
End If
Next
Return sql
End Function
这还没有经过测试,它可能会变得更有效率,但它应该能让你继续前进。无论您在应用程序中的何处执行 sql,只需将 sql 包装在此函数中以在执行前清理字符串:
ExecuteSQL(MakeSQLSafe(strSQL))
希望有帮助
于 2009-04-08T11:05:06.957 回答
0
与任何字符串清理一样,您最好使用指示允许哪些字符的白名单,而不是使用不允许的字符的黑名单。
这个关于过滤 HTML 标签的问题导致了一个接受的答案,建议使用正则表达式来匹配白名单:如何过滤除某个白名单之外的所有 HTML 标签?- 我建议你做一些非常相似的事情。
于 2009-04-08T11:27:16.090 回答
0
我正在使用 URL 路由,我发现这很好用,将 URL 的每个部分传递给这个函数。它比您需要的更多,因为它将“&”等字符转换为“and”,但您可以修改它以适应:
public static string CleanUrl(this string urlpart) {
// convert accented characters to regular ones
string cleaned = urlpart.Trim().anglicized();
// do some pretty conversions
cleaned = Regex.Replace(cleaned, " ", "-");
cleaned = Regex.Replace(cleaned, "#", "no.");
cleaned = Regex.Replace(cleaned, "&", "and");
cleaned = Regex.Replace(cleaned, "%", "percent");
cleaned = Regex.Replace(cleaned, "@", "at");
// strip all illegal characters like punctuation
cleaned = Regex.Replace(cleaned, "[^A-Za-z0-9- ]", "");
// convert spaces to dashes
cleaned = Regex.Replace(cleaned, " +", "-");
// If we're left with nothing after everything is stripped and cleaned
if (cleaned.Length == 0)
cleaned = "no-description";
// return lowercased string
return cleaned.ToLower();
}
// Convert accented characters to standardized ones
private static string anglicized(this string urlpart) {
string beforeConversion = "àÀâÂäÄáÁéÉèÈêÊëËìÌîÎïÏòÒôÔöÖùÙûÛüÜçÇ’ñ";
string afterConversion = "aAaAaAaAeEeEeEeEiIiIiIoOoOoOuUuUuUcC'n";
string cleaned = urlpart;
for (int i = 0; i < beforeConversion.Length; i++) {
cleaned = Regex.Replace(urlpart, afterConversion[i].ToString(), afterConversion[i].ToString());
}
return cleaned;
// Spanish : ÁÉÍÑÓÚÜ¡¿áéíñóúü"
}
于 2009-04-13T20:48:14.973 回答