ASP實現搜索關鍵字高亮

用ASP實現搜索引擎的功能是一件很方便的事,可是,如何實現類似3721的智能搜索呢?比如,當在搜索條件框內輸入“中國人民”時,自動從中提取“中國”、“人民”等關鍵字並在數據庫內進行搜索。看完本文後,你就可以發現,這個功能實現起來竟然是如此的簡單。
第一步,我們要建立一個名爲db_sample.mdb的數據庫(本文以Access2000數據庫爲例),並在其中建立表T_Sample。表T_Sample包括如下字段:

ID 自動編號
   U_Name 文本
   U_Info 備註

第二步,我們開始設計搜索頁面Search.asp。該頁面包括一個表單(Frm_Search),表單內包括一個文本框和一個提交按鈕。並將表單的method屬性設爲“get” ,action屬性設爲“Search.asp",即提交給網頁自身。代碼如下:

以下是代碼片段:

<!-- Search.asp -->  
<form name="frm_Search" method="get" action="Search.asp">  
請輸入關鍵字:  
<input type="text" name="key" size="10">  
<input type="submit" value="搜索">  
</form>

下面,就進入了實現智能搜索的關鍵部分。

首先,建立數據庫連接。在Search.asp的開始處加入如下代碼:

以下是代碼片段:

<%  
  Dim strProvider,CNN  
  strProvider="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="  
  strProvider=strProvider & Server.MapPath("\") & "\data\db_Sample.mdb" '假設數據庫存放在主頁根目錄下的data目錄下  
  Set CNN = Server.CreateObject("ADODB.connection")  
  CNN.Open strProvider 打開數據庫連接  
%>

接下來,判斷 ASP頁所接收到的數據,並在數據庫中進行搜索。

以下是代碼片段:

<font color="#FF0000">未找到任何結果!!!</font>  
<%  
Else  
%> 

搜索名稱爲“<font color="#FF0000"><%= S_Key %></font>”的項,共找到 <font color="#FF0000"><%= RST.RecordCount %></font> 項:<p>

<%  
While Not RST.EOF 遍歷整個記錄集,顯示搜索到的信息並設置鏈接  
%>  
<!-- 此處可設爲你所需要的鏈接目標 -->  
<font style="font: 12pt 宋體"><a href="info.asp?ID=<%= RST("ID") %>" target="_blank"><%= RST("U_Name") %></a></font>  
<!-- 顯示部分詳細內容 -->  
<font style="font: 9pt 宋體"><%= Left(RST("U_Info"),150) %></font><p>  
<%  
  RST.MoveNext  
  Wend  
   RST.Close  
   Set RST=Nothing  
  End If  
End If  
%>

在上面的代碼中,有一個自定義函數 AutoKey ,該函數是實現智能搜索的核心所在。代碼如下:

以下是代碼片段:

<%  
Function AutoKey(strKey)  
CONST lngSubKey=2  
Dim lngLenKey, strNew1, strNew2, i, strSubKey

'檢測字符串的合法性,若不合法則轉到出錯頁。出錯頁你可以根據需要進行設定。

if InStr(strKey,"=")<>0 or InStr(strKey,"`")<>0 or InStr(strKey,"")<>0 or InStr(strKey," ")<>0 or InStr(strKey," ")<>0 or InStr(strKey,"")<>0 or InStr(strKey,chr(34))<>0 or InStr(strKey,"\")<>0 or InStr(strKey,",")<>0 or InStr(strKey,"<")<>0 or InStr(strKey,">")<>0 then  
Response.Redirect "error.htm"  
End If  
lngLenKey=Len(strKey)  
Select Case lngLenKey  
Case 0 '若爲空串,轉到出錯頁  
Response.Redirect "error.htm"  
Case 1 '若長度爲1,則不設任何值  
strNew1=""  
strNew2=""  
'Case Else 若長度大於1,則從字符串首字符開始,循環取長度爲2的子字符串作爲查詢條件  
For i=1 To lngLenKey-(lngSubKey-1)  
strSubKey=Mid(strKey,i,lngSubKey)  
strNew1=strNew1 & " or U_Name like %" & strSubKey & "%"  
strNew2=strNew2 & " or U_Info like %" & strSubKey & "%"  
Next  
End Select  
'得到完整的SQL語句

AutoKey="Select * from T_Sample where U_Name like %" & strKey & "% or U_Info like %" & strKey & "%" & strNew1 & strNew2  
End Function  
%>

要實現智能搜索,其核心就是將搜索關鍵字進行自動分組。在此處,我們使用了循環取長度爲2的子串的方法。爲什麼不將子串長度定爲1、3、4或其他呢?這是因爲若子串長度小於2即爲1時,會失去將關鍵字分組的功能,而若子串長度大於2,則會丟失一些詞組。大家可以將 CONST lngSubKey=2改爲其他數字試一試,孰優孰劣自見分曉。

最後,別忘了將數據連接關閉,以釋放資源。

以下是代碼片段:

<%  
CNN.Close  
Set CNN=Nothing  
%>

至此,這個智能搜索引擎已經完成了。你還可以將其繼續完善,比如添加分頁、突出顯示等功能。

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