I'm writing a forum-type discussion board in Perl and would like to change automatically http://www.google.com to be an HTML link. This should also be safe, and err on the side of security. Is there a quick, easy, and safe way to add links automatically?
+6
A:
Try something like this:
use Regexp::Common qw /URI/;
$text =~ s|($RE{URI}{HTTP})(?!</a>)|<a href="$1">$1</a>|g
The key here is using Regexp::Common::URI which probably has a more thorough url matcher than anything I could come up with. Also I do a negative lookahead assertion at the end to make sure that the url is not already in a link. That last part isn't exactly thorough, since it's possible that somebody could do something like this:
<a href="http://www.mysite.com">http://www.mysite.com is my website</a>
To do this correctly you'd need to parse the entire submission text and only substitute out urls that are not already part of a link.
bmdhacks
2009-05-08 15:05:02
See http://stackoverflow.com/questions/819144/stripping-an-url-from-a-text/819972#819972
Sinan Ünür
2009-05-08 17:56:35