Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically create email link from a static text

I'm trying to figure out how to automatically link the email addresses contained in a simple text from the db when it's printed in the page, using php.

Example, now I have:

Lorem ipsum dolor [email protected] sit amet

And I would like to convert it (on the fly) to:

Lorem ipsum dolor <a href="mailto:[email protected]">[email protected]</a> sit amet 
like image 913
Raffaele Avatar asked Mar 09 '09 15:03

Raffaele


2 Answers

You will need to use regex:

<?php

function emailize($text)
{
    $regex = '/(\S+@\S+\.\S+)/';
    $replace = '<a href="mailto:$1">$1</a>';

    return preg_replace($regex, $replace, $text);
}


echo emailize ("bla bla bla [email protected] bla bla bla");

?>

Using the above function on sample text below:

blalajdudjd [email protected] djjdjd 

will be turned into the following:

blalalbla <a href="mailto:[email protected]">[email protected]</a> djjdjd
like image 150
Erick Avatar answered Nov 08 '22 11:11

Erick


Try this version:

function automail($str){

    //Detect and create email
    $mail_pattern = "/([A-z0-9_-]+\@[A-z0-9_-]+\.)([A-z0-9\_\-\.]{1,}[A-z])/";

    $str = preg_replace($mail_pattern, '<a href="mailto:$1$2">$1$2</a>', $str);

    return $str;
}

Update 31/10/2015: Fix for email address like [email protected]

function detectEmail($str)
{
    //Detect and create email
    $mail_pattern = "/([A-z0-9\._-]+\@[A-z0-9_-]+\.)([A-z0-9\_\-\.]{1,}[A-z])/";
    $str = preg_replace($mail_pattern, '<a href="mailto:$1$2">$1$2</a>', $str);

    return $str;
}
like image 30
NothingCtrl Avatar answered Nov 08 '22 11:11

NothingCtrl