Find and Replace Hyperlinks and Email Addresses in PHP

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>
Author avatar

About the author

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.