PDA

View Full Version : Efficent way of stripping a url out of a string?


element78
01-01-2004, 08:31 PM
Say you have a string with the value of:

<html>
<body>
<a href=http://www.google.com/>Google</a><br>
<a href=http://www.yahoo.com/>Yahoo</a>
</body></html>

Is there any possible way of say grabbing those URLs and putting them into a listbox with Item Text as Google, and Item Data as http://www.google.com/ and so on?

I've run into a need for this several times, and never bothered to ask about it. But it sure would be nice to know. :)

Brett
01-02-2004, 09:54 AM
There are a lot of ways to go at it, but here is one that should be fairly easy to understand:

strText = [[<html>
<body>
<a href=http://www.google.com/>Google</a><br>
<a href=http://www.yahoo.com/>Yahoo</a>
</body></html>]];

strAnchor = "<a href=";
nAnchorLength = String.Length(strAnchor);
strEndAnchor = "</a>";
nEndAnchorLength = String.Length(strEndAnchor);

nFoundPos = String.Find(strText,strAnchor,1,false);
while(nFoundPos ~= -1)do
-- Find the end bracket...
nEndPos = String.Find(strText,">",nFoundPos+nAnchorLength,false);
if(nEndPos ~= -1)then
-- OK, we have the URL...
strURL = String.Mid(strText,nFoundPos+nAnchorLength,nEndPos-(nFoundPos+nAnchorLength));

-- Now find the label...
nEndAnchorPos = String.Find(strText,strEndAnchor,nEndPos,false);
if(nEndAnchorPos ~= -1)then
strLabel = String.Mid(strText,nEndPos+1,nEndAnchorPos-nEndPos-1);

-- Now we have the label and URL, insert them into list box
-- or whatever here... for illustration we will just show them
-- in a dialog...
Dialog.Message(strLabel,strURL);
end
end
nFoundPos = String.Find(strText,strAnchor,nFoundPos+nAnchorLen gth,false);
end