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);


Using parseHyperlinks(), becomes:

<a href=""></a>

And using parseEmails(), becomes:

<a href="">></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.