MrJ
MrJ

Reputation: 1938

Linking email addresses that aren't already linked

I'm currently matching email addresses with the below regex (and linking them as mailto links):

/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,64})/

However, I do not want to link anything that has already been linked before as a mailto link or within an existing link (eg. [email protected]) otherwise the link gets quite screwed up like the below:

<a href="mailto:<a href="mailto:[email protected]">[email protected]</a>"><a href="mailto:[email protected]">[email protected]</a></a>

Update

Here's an example of PHP I'm using to find the email addresses (sorry, didn't think it was required):

$input = "[email protected]<br><br><a href='mailto:[email protected]'>test email</a><br><br><a href='mailto:[email protected]'>[email protected]</a>";

$output = preg_replace("/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,64})/i", "<a href='mailto:$1'>$1</a>", $input);

//output
<a href="mailto:[email protected]">[email protected]</a><br><br><a mailto:[email protected]'="" href="mailto:&lt;a href=">[email protected]</a>'&gt;test email<br><br><a mailto:[email protected]'="" href="mailto:&lt;a href=">[email protected]</a>'&gt;<a href="mailto:[email protected]">[email protected]</a>

Update 2

I also have a further regex question (if possible) - I also have the below regex to make all links target to a new window, however, i do not want anything mailto linked to go to a new window - is it possible to not target mailto links?

$output = preg_replace("/<(a)([^>]+)>/i", "<\\1 target=\"_blank\"\\2>", str_replace('target="_blank"', '', $output));

Upvotes: 3

Views: 211

Answers (1)

Nikola Malešević
Nikola Malešević

Reputation: 1858

How about this regex?

/((?<!mailto:|=|[a-zA-Z0-9._%+-])[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.‌​-]+\.[a-zA-Z]{2,64}(?![a-zA-Z]|<\/[aA]>))/

Upvotes: 3

Related Questions