Reputation: 93
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
Upvotes: 8
Views: 17017
Reputation: 2666
Here's some code I combined (from answers on here) for a function to do this for emails and URLs:
The benefit of this is it does not convert to a link if one is already there.
function replace_links( $content ){
$content = preg_replace('"<a[^>]+>.+?</a>(*SKIP)(*FAIL)|\b(?:https?)://\S+"', '<a href="$0">$0</a>', $content);
$content = preg_replace('"<a[^>]+>.+?</a>(*SKIP)(*FAIL)|\b(\S+@\S+\.\S+)\S+"', '<a href="mailto:$0">$0</a>', $content);
return $content;
}
Demo: https://glot.io/snippets/g6nwd6amyo
I also suggest looking at how WordPress handles this, as you know it's battle tested and deals with random issues like periods or other characters after the actual email:
https://github.com/WordPress/WordPress/blob/master/wp-includes/formatting.php#L2997-L3055
Look at make_clickable
and specifically _make_email_clickable_cb
callback line (this is personally what i ended up using instead due to other regex issues)
Upvotes: 1
Reputation: 305
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;
}
Upvotes: 16
Reputation: 6089
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
Upvotes: 24
Reputation: 7445
I think this is what you want...
//store db value into local variable
$email = "[email protected]";
echo "<a href='mailto:$email'>Email Me!</a>";
Upvotes: -2