How to Easily Parse Text With ASP

by admin on July 24, 2009 · 0 comments

Parsing text in ASP is not the easiest task. If you only want to extract text from the right or left side of a string, it's no problem. But if you need to extract from the middle of the string – or parse HTML or XML tags or attributes – it can be quite difficult if you don't know the exact location. So I built this function to take a string, and two other strings as the left and right markers to parse between.

The function has two additional capabilities besides just parsing between two strings.
1. If you specify "1" as the strLft parameter, all text from the beginning of the string to the instance of the right string will be parsed. Basically this means "give me everything before ___ text"
2. If you use empty quotes for the left parameter ("”), then everything after the right marker will be parsed. This is handy if you have repeating tags, and you want to parse them one at a time. You parse the first one, then remove it by parsing everything to the right of it, parse the next, and so on.

'=== extractor function
'=== strSrc: the text to pull from
'=== strLft: left marker to start at
'=== strRgt: right marker to end at
function parser(strSrc, strLft, strRgt)
        dim strParsed
        strLft = cStr(strLft)
       
        if strLft = "1" then '=== start from beginning
                if inStr(strSrc, strRgt) > 0 then strParsed = left( strSrc, inStr(strSrc, strRgt)1)   
        elseif strLft = "" then '=== start from right marker (trim out last result)
                if inStr(strSrc, strRgt) > 0 then strParsed = right( strSrc, len(strSrc)(inStr(strSrc, strRgt) + len(strRgt)1))
        else
                if inStr(strSrc, strLft) > 0 then
                        strParsed = right( strSrc, len(strSrc)(inStr(strSrc, strLft) + len(strLft)1))
                        if inStr(strSrc, strRgt) > 0 then strParsed = left( strParsed, inStr(strParsed, strRgt)1)
                end if
        end if
       
        strParsed = trim(strParsed)
       
        do until left(strParsed, 1) <> chr(10) and right(strParsed, 1) <> chr(10)
                if left(strParsed, 1) = chr(10) then strParsed = right(strParsed, len(strParsed)1)
                if right(strParsed, 1) = chr(10) then strParsed = left(strParsed, len(strParsed)1)
        loop
       
        strParsed = replace( strParsed, "%20", " ")
        strParsed = trim(strParsed)
       
        parser = strParsed
end function

Previous post:

Next post: