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
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With