Mega Code Archive

 
Categories / Delphi / LAN Web TCP
 

Decorate url`s (plain text to HTML conversion)

Title: Decorate url`s (plain text to HTML conversion) Question: How to decorate url's while plain text to HTML conversion (replace http://delphi3000.com with delphi3000.com) Answer: There are two ways. The tradional one - You must make full featured text parser. This is an awful peace of work ! For example, try to implement rules for URL search ;) The second - look at the text from bird's eye view with help of regular expressions engine. Your application will be implemented very fast and will be robust and easy to support ! Unfortunately, Delphi component palette contains no TRegularExpression component. But there are some third-party implementations. I'll use in my examples the TRegExpr (You can download it from http://anso.virtualave.net/delphi_stuff.htm). uses RegExpr; type TDecorateURLsFlags = (durlProto, durlAddr, durlPort, durlPath, durlBMark, durlParam); TDecorateURLsFlagSet = set of TDecorateURLsFlags; function DecorateURLs (const AText : string; AFlags : TDecorateURLsFlagSet = [durlAddr, durlPath] ) : string; const URLTemplate = '(?i)' + '(' + '(FTP|HTTP)://' // Protocol + '|www\.)' + '([\w\d\-]+(\.[\w\d\-]+)+)' // TCP addr / domain name + '(:\d\d?\d?\d?\d?)?' // port number + '(((/[%+\w\d\-\\\.]*)+)*)' // unix path + '(\?[^\s=&]+=[^\s=&]+(&[^\s=&]+=[^\s=&]+)*)?' // request params + '(#[\w\d\-%+]+)?'; // bookmark var PrevPos : integer; s, Proto, Addr, HRef : string; begin Result := ''; PrevPos := 1; with TRegExpr.Create do try Expression := URLTemplate; if Exec (AText) then REPEAT s := ''; if CompareText (Match [1], 'www.') = 0 then begin Proto := 'http://'; Addr := Match [1] + Match [3]; HRef := Proto + Match [0]; end else begin Proto := Match [1]; Addr := Match [3]; HRef := Match [0]; end; if durlProto in AFlags then s := s + Proto; // Match [1] + '://'; if durlAddr in AFlags then s := s + Addr; // Match [2]; if durlPort in AFlags then s := s + Match [5]; if durlPath in AFlags then s := s + Match [6]; if durlParam in AFlags then s := s + Match [9]; if durlBMark in AFlags then s := s + Match [11]; Result := Result + System.Copy (AText, PrevPos, MatchPos [0] - PrevPos) + '' + s + ''; PrevPos := MatchPos [0] + MatchLen [0]; UNTIL not ExecNext; Result := Result + System.Copy (AText, PrevPos, MaxInt); // Tail finally Free; end; end; Note, that You can easely extract any part of URL (see AFlags parameter). Conclusion "Free Your mind" ((c) The Matrix ;)) and You'll find many other tasks there regular expressions can save You incredible part of stupid coding work ! P.S. Sorry for terrible english. My native language is Pascal ;)