tags:

views:

153

answers:

1

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"&gt;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
See http://stackoverflow.com/questions/819144/stripping-an-url-from-a-text/819972#819972
Sinan Ünür