Crop the First Sentence

Using the Instr function we can check to find if there is a full stop in our string and if there is then find it's position. Next using the Left function we can return a specified number of characters from the left including the first full stop.

Below is sample code that will retrieve the headline and first sentence of the news story for each news article in our database 'News.mdb'. The fields in our database are an 'ID' autonumber, 'headline' which is a text field and 'news_story' which is a memo field.

<%@ Language="VBScript" %>
<% Option Explicit %>
<html>
<head>
<title>Crop the first sentence</title>
</head>
<body>
<%

'Declare your variables
Dim oConnection, oRecordset, iFirst
Dim sSQL, sConnString, sNewsTitle, sNewsBody

'declare SQL statement that will query the database
sSQL="SELECT * FROM tblNews"

'define the connection string, specify database
'driver and the location of database
sConnString="PROVIDER=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Server.MapPath("News.mdb")


'create an ADO connection and recordset
Set oConnection = Server.CreateObject("ADODB.Connection")
Set oRecordset = Server.CreateObject("ADODB.Recordset")

'Open the connection to the database
oConnection.Open(sConnString)

'Open the recordset object, execute the SQL statement
oRecordset.Open sSQL, oConnection

'first of all determine whether there are any records
If oRecordset.EOF Then
Response.Write("There are no news articles.")
Else
'If there are records then loop through the fields
Do While Not oRecordset.EOF
sNewsTitle= oRecordset("headline")
sNewsBody= oRecordset("news_story")
'Call function InStr, if Function returns a number > than 0 then there's a fullstop
If InStr(1, sNewsBody, ".") > 0 Then
'Call function InStr again, the Function will return the position of the first fullstop
iFirst=InStr(1,sNewsBody,".")
'Use Left function to return all characters including the fullstop
sNewsBody=Left(sNewsBody,iFirst)
End If
Response.write "<p>"
Response.Write sNewsTitle & "<br>" 'insert a line break
Response.Write sNewsBody
Response.Write "</p>" 
'move on to the next record
oRecordset.MoveNext
Loop
End If

'close the connection and recordset objects and free up resources
oRecordset.Close
oConnection.Close
Set oRecordset = Nothing
Set oConnection = Nothing
%>

</body>
</html>

Get the best asp web hosting provider now and save 30%

Advertisements



MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.

Free ASP Hosting