將用戶輸入的字符串轉換爲可換行、替換Html編碼、無危害數據庫特殊字符、去掉首尾空白、的安全方便代碼

public static string ConvertStr(string inputString)
        {
            
string retVal = inputString;
            retVal 
= retVal.Replace("&""&");
            retVal 
= retVal.Replace("/""""");
            retVal = retVal.Replace("<""&lt;");
            retVal 
= retVal.Replace(">""&gt;");
            retVal 
= retVal.Replace(" ""&nbsp;");
            retVal 
= retVal.Replace("  ""&nbsp;&nbsp;");
            retVal 
= retVal.Replace("/t""&nbsp;&nbsp;");
            retVal 
= retVal.Replace("/r""<br>");
            
return retVal;
        }

        
private static string FetchURL(string strMessage)
        {
            
string strPattern = @"(?<url>(http|ftp|mms|rstp|news|https)://(?:[/w-]+/.)+[/w-]+(?:/[/w-./?%&~=]*[^./s|,|/)|<|!])?)";
            
string strReplace = "<a href=/"${url}/" target=_blank>${url}</a>";
            
string strInput = strMessage;
            
string strResult;
            strResult 
= Regex.Replace(strInput, strPattern, strReplace);
            strPattern 
= @"(?<!http://)(?<url>www/.(?:[/w-]+/.)+[/w-]+(?:/[/w-./?%&~=]*[^./s|,|/)|<|!])?)";
            strReplace 
= "<a href=/"http://${url}/" target=_blank>${url}</a>";
            strResult = Regex.Replace(strResult, strPattern, strReplace);
            
return strResult;
        } 

        
public string ToUrl(string inputString)
        {
            
string retVal = inputString;
            retVal 
= ConvertStr(retVal);
            retVal 
= FetchURL(retVal);
            
return retVal;
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章