用過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實作類別似的變數名-值變換。
思路
首先,必須有一個方法把需要用實際值替換的變數名與普通的文本區分出來;然後,把所有找到的變數名用它所代表的實際值替換掉。
對於第一點可以通過Regex尋找得到,這裡我們不採用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
實現
完整代碼:
'=================================================================
'DESIGN BY : 彭國輝
'SITE: http://kacarton.yeah.net/
'BLOG: http://blog.csdn.net/nhconch
'EMAIL: kacarton@sohu.com
'文章為作者原創,轉載前請先與本人聯絡,轉載請註明文章出處、保留作者資訊,謝謝支援!
'=================================================================
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)還允許對字串值進行四則運算。