An implementation for converting a plaintext URL to a link, brought up in the post The Problem With URLs. This is useful for a custom comment or feedback system, but we’ll forget gopher:// links (sorry.)

The problem with the regular expression provided in the above URL is that when it’s mixed with HTML content, matching the pattern


will turn it into

since ” is a non-word character. I found the conclusion to just not use parenthesis in links to be pretty defeatist as common usages in MSDN and Wikipedia can be handled with relative ease. You must provide additional string processing, which is an absolute headache in Java but here I go. 10 lines for the original outline turns into almost 50. (We are going to ignore that user-generated text shouldn’t allow the <img> tag. Sometimes the client wants it and you just roll with it, son.)

Java implementation

PHP implementation

Mixing up ereg*() and preg*() functions like there’s no tomorrow:

This is obviously not the most elegant solution as this code still makes plenty of assumptions (especially as to the location of an URL placed in an already existing <a ...> tag) and it really just highlights how you can’t handle every situation where a user throws a link onto their glob of unformatted text. But they’ll still yell at you for it not working right.