A Beautiful Site

Find and replace hyperlinks and email addresses in PHP

A drawing of a cartoon man pointing upwards

Heads up! This post was written in 2007, so it may contain information that is no longer accurate. I keep posts like this around for historical purposes and to prevent link rot, so please keep this in mind as you're reading.

— Cory

These two PHP functions use regular expressions to add the appropriate HTML anchor tags around hyperlinks and email addresses in $string.

PHP code #

function parseHyperlinks($string) {
  // Add  tags around all hyperlinks in $string
  return ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "\0", $string);

function parseEmails($string) {
  // Add  tags around all email addresses in $string
  return ereg_replace("[_A-Za-z0-9-]+(.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(.[A-Za-z0-9-]+)*(.[A-Za-z]{2,3})", "\0", $string);

Output #

Using parseHyperlinks(), http://domain.com/index.htm becomes:

<a href="http://domain.com/index.htm">http://domain.com/index.htm</a>

And using parseEmails(), email@domain.com becomes:

<a href="mailto:email@domain.com">email@domain.com></a>