链接尚未链接的电子邮件地址

时间:2012-09-03 12:44:52

标签: php regex replace

我目前正在使用以下正则表达式匹配电子邮件地址(并将其链接为mailto个链接):

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

但是,我不希望将之前已链接过的任何内容链接为mailto链接或现有链接(例如index.php?email=example@example.com),否则链接会获取像下面这样搞得搞砸了:

<a href="mailto:<a href="mailto:example@example.com">example@example.com</a>"><a href="mailto:example@example.com">example@example.com</a></a>

更新

以下是我用来查找电子邮件地址的PHP示例(抱歉,不认为是必需的):

$input = "example@example.com<br><br><a href='mailto:example@example.com'>test email</a><br><br><a href='mailto:example@example.com'>example@example.com</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:example@example.com">example@example.com</a><br><br><a mailto:example@example.com'="" href="mailto:&lt;a href=">example@example.com</a>'&gt;test email<br><br><a mailto:example@example.com'="" href="mailto:&lt;a href=">example@example.com</a>'&gt;<a href="mailto:example@example.com">example@example.com</a>

更新2

我还有一个正则表达式问题(如果可能的话) - 我也有以下正则表达式使所有链接都指向一个新窗口,但是,我不希望任何链接的mailto转到一个新窗口 - 是否可以不定位mailto个链接?

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

1 个答案:

答案 0 :(得分:3)

这个正则表达式怎么样?

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