Search code examples
phpregexemailprefix

Regex email text with prefix and suffix


I have two cases of html/text:

  1. My email is username@domen.com
  2. My email is <a href="mailto:username@domen.com">username@domen.com</a>

Also, I have function which is searching for email-links like and replace them with <a href="email@address">email@address</a> pattern, and it works. BUT, what if text already contains email-links. I don't want matching them too.

function make_email_links($text)
{
  return  preg_replace(
     array('/(([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@([A-Za-z0-9-]+)
       (\\.[A-Za-z0-9-]+)*)/iex'
       ),
     array( 
       "stripslashes((strlen('\\2')>0?'<a href=\"mailto:\\0\">\\0</a>':'\\0'))" 
       ),
       $text
   );
}

I tried with

'/((^<a) .......... )/iex'

but it was unsuccessful. How to match only email-links like text but not real email-links?


Solution

  • You should try this:

    $formattedTest = preg_replace("#(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $text);
    

    I used the old one (this won't work!):

    $formattedTest = preg_replace('/([\w\.!#\$%\-+.]+@[A-Za-z0-9\-]+(\.[A-Za-z0-9\-]+)+)/', '<a href="mailto:\\1">\\1</a>', $text);
    

    But as you said it would have duplicated my email even if it's already inside an tag.