Recently I was developing a custom solution for one of my client’s projects and I encountered a problem: A message (string) was stored in the database which may contain urls. I had to display that message and if it contains urls – it had to be display as active, clickable links. So here’s what worked for me:

PHP Snippet: Find URLs in string and make links using a function

$yourTextWithLinks = 'Here is an example for a text (string) that contains one or more url. Just visit http://www.google.com/ or <a href="http://www.google.com" rel="nofollow">http://google.com</a> and this is the end of the example.';
$text = strip_tags($yourTextWithLinks);

function displayTextWithLinks($s) {
  return preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1">$1</a>', $s);
}

$text = displayTextWithLinks($text);
echo $text;

Normally if you echo the variable $yourTextWithLinks it will display plain text with no active links. So now you can pass your string to the displayTextWithLinks() function and will return a text with clickable links in it.

If you’d like to use it without a function, here’s how.

PHP Snippet: Find URLs in text and make links without a function

$text = strip_tags($yourTextWithLinks);
$textWithLinks = preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank" rel="nofollow">$1</a>', $text);
echo $textWithLinks;

Learn more about: