In a content management system I was working on at work we noticed there was a couple of problems with how the URLs entered by users broke our web site due to their length. We also had a request to automatically turn hand typed URLs into links, so here is what I did in C#

Added the RegEx namespace:

using System.Text.RegularExpressions;


Here is the method I added to our utility class:

public string URLsToHyperlinks(string sInput)<br /> {<br /> return Regex.Replace(sInput, @&quot;(\bhttp://[^ ]+\b)&quot;, @&quot;&lt;a href=&quot;&quot;$0&quot;&quot;&gt;$0&lt;/a&gt;&quot;);<br /> }

Here is a function that does the same thing only in PHP

function urls_to_hyperlinks($text)<br /> {<br /> return preg_replace( &quot;`((http)+(s)?:(//)|(www\.))((\w|\.|\-|_)+)(/)?(\S+)?`i&quot;, &quot;&lt;a href=\&quot;http\\3://\\5\\6\\8\\9\&quot; title=\&quot;\\&quot; target=\&quot;_blank\&quot;&gt;\\5\\6&lt;/a&gt;&quot;, $text); <br /> }



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: