Replace URLs with links - PHP

  • Technologies: PHP, HTML
  • Difficulty: Easy
  • Time: 5 minutes

Where I work, we develop many websites that have blogs and news sections. Often we allow users to add their own HTML snippets into the content of the articles in order to enhance the look and feel of the story.

The Problem

We often find that different users have different levels of experience when it comes to "the web". Some people tend to enter invalid HTML which can compromise the design, layout, functionality and many other things.

Soooo with trying to keep all HTML snippets at a minium I wanted to find a way in which users can add links which adding any HTML at all.

So for example: &

Would become the following AUTOMATICALLY: &

The Solution

With this CMS we were using PHP and it would be a great idea to create some regular expression rules in order to find a matching criteria. 

The Code

function replace_links( $text ) 

$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);

$ret = ' ' . $text;

$ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1\\2", $ret);

$ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1\\2", $ret);

$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1\\2@\\3", $ret);

$ret = substr($ret, 1);
return $ret;


comments powered by Disqus