【发布时间】:2012-09-03 12:44:51
【问题描述】:
我目前正在使用以下正则表达式匹配电子邮件地址(并将它们链接为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:<a href=">example@example.com</a>'>test email<br><br><a mailto:example@example.com'="" href="mailto:<a href=">example@example.com</a>'><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));
【问题讨论】:
-
您需要在实际执行链接的位置提供代码 sn-p。简单的正则表达式模式是不够的。
-
不认为它是必需的(因为正则表达式是正则表达式),现在包括
-
不是每个正则表达式都是正则表达式。不同的语言允许不同的功能。例如,lookbehinds 在 .NET 中有效,但在 JavaScript 中无效。这就是为什么我们需要知道您使用什么语言来处理正则表达式。