我需要过滤掉/? - ^%{} []; $ = *`#|& @'\“<>()+,\等字符。我需要用空字符串替换它它在查询字符串中。请帮帮我。我在ASP页面中使用它。
答案 0 :(得分: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))
希望有所帮助
答案 1 :(得分:0)
与任何字符串清理一样,您最好使用白名单来决定 允许哪些字符,而不是不的黑名单
关于过滤HTML标记的问题产生了一个可接受的答案,建议使用正则表达式来匹配白名单:How do I filter all HTML tags except a certain whitelist? - 我建议您做一些非常相似的事情。
答案 2 :(得分:0)
我正在使用URL路由,我发现这很有效,将URL的每个部分都传递给此函数。这比你需要的更多,因为它转换像“&amp;”这样的字符到“和”,但你可以修改它以适应:
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 : ÁÉÍÑÓÚÜ¡¿áéíñóúü"
}