views:

437

answers:

2

Hi, 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
A: 

I think this is what you want...

  //store db value into local variable
    $email = "[email protected]";
    echo "<a href='mailto:$email'>Email Me!</a>";
Dan Appleyard
no, he probably needs regex to find and replace any emails in the text.
dusoft
exactly, convert the email address contained in the text to a "mailto" link with the surrounding text intact
Raffaele
then nevermind....
Dan Appleyard
+4  A: 

You will need to use regex:

<?php

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

  $result = preg_replace($regex, $replace, $text);

  return $result;

  preg_match($regex, $text, $e);

  var_dump($e);
}


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

?>

With that blalajdudjd [email protected] djjdjd will be turned into blalalbla <a href="mailto:[email protected]">[email protected]</a> djjdjd

Erick
thanks, I tried but it seem to not work. I've passed the text via "$text" and put an "echo $result;" after the } but nothing come out. Maybe I'm doing a stupid error, I'm just started to learn php.
Raffaele
Yup, I tested it and didn't worked at first. I just retested it. Now it works like a charm. If youw ant to see the ouput of the regex just comment out the preg_replace / return part. Otherwise the preg_match/var_dump wont be displayed ;-)
Erick
Thanks, now it work perfectly!
Raffaele