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@foo.com sit amet
And I would like to convert it (on the fly) to:
Lorem ipsum dolor <a href="mailto:email@foo.com">email@foo.com</a> sit amet
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 e@mail.com bla bla bla");
?>
Using the above function on sample text below:
blalajdudjd user@example.com djjdjd
will be turned into the following:
blalalbla <a href="mailto:user@example.com">user@example.com</a> djjdjd
I think this is what you want...
//store db value into local variable
$email = "foo@bar.com";
echo "<a href='mailto:$email'>Email Me!</a>";
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 abc.def@xyz.com
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;
}