nhconch [原作] 用過PHP的朋友都知道,PHP中變量的使用靈活方便,特別是能在字符串中方便實現變量名-值變換,使得整個PHP代碼更顯簡潔優美。比如一條更新數據庫的SQL語句只需寫成:"update users set password='$password', group=$group, name='$username' where account='$account'",其中的$password、$group、$username、$account便會被實際的變量值替換,而在ASP中要實現相同的功能必須寫成:"update useres set password='" & password & "',group=" & group & ",name='" & username & "' where account='" & account & "'",顯得冗長難看。如果這是一條insert語言而且插入的字段內容很多的話,那么查看字段與values的對應關系將會是一個痛苦的過程。 現在讓我們看看如何在ASP實現類似的變量名-值變換。 思路 首先,必須有一個方法把需要用實際值替換的變量名與普通的文本區分出來;然后,把所有找到的變量名用它所代表的實際值替換掉。 對于第一點可以通過正則表達式查找得到,這里我們不采用PHP的變量表示方式,而采用大托號{}作為變量名的邊界符,字符串表示變為password='{password}',group={group}。 第二點是變量名-值變換的關鍵,通過變量名得到變量值。查看ASP資料沒有找到直接實現的方法,但有一個函數Execute引起我們的注意,從資料說明中可知Execute可以執行傳入的有效的字符串作為代碼執行同,這樣只要編寫一個小函數就可以實現我們的要示。核心代碼為: function GetVar(var_name) Execute("function get_value(): get_value=" & var_name & ": end function") getvar=get_value() end function 實現 完整代碼: function GetVar(var_name) Execute("function get_value(): get_value=" & var_name & ": end function") getvar=get_value() end function function Txt2Value(str, level) dim regEx, Matches, Result Set regEx = new RegExp select case level case 0 regEx.Pattern = "\{(\w+)\}" '變量名有效 case 1 regEx.Pattern = "\{([\w+\-\*/\\<>=]+)\}" '變量名及運算符有效 'case 2 regEx.Pattern = "\{([\w\s]+)\}" '除換行符外的所有字符有效 case else exit function end select 'regEx.Pattern = "\{(\w+)\}" regEx.IgnoreCase = true regEx.Global = true Set Matches = regEx.Execute(str) Result = str 'response.write Matches.Count For Each Match In Matches Result = Replace(Result, Match.Value, GetVar(Match.SubMatches(0))) Next set Matches = nothing set regEx = nothing Txt2Value = Result end function function Var2Value(var_name) Var2Value = Txt2Value(var_name, 0) end Function 調用方法: Var2Value("update users set password='{password}', group={group}, name='{username}' where account='{account}'" Var2Value調用了Txt2Value,Txt2Value找出所有變量名交調用GetVar得到變量值并進行替換。實際上直接調用Txt2Value(str,1)還允許對字符串值進行四則運算。
|