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

标签 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));

最佳答案

这个正则表达式怎么样?

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

关于php - 链接尚未链接的电子邮件地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12248159/

相关文章:

php - 删除具有特定条件的行内的div

php - 数组只存储一个值而不是多个

java - 提取嵌套大括号内的数据

regex - Sed 正则表达式多行 - 替换 HTML

javascript - 将部分不同类名替换为数据属性

php - Laravel - 如何通过 hasMany 中的相关属性进行排序

php - Apache(HTTPD)启用目录/文件写入和文件上传需要哪些配置?

regex - 如何在postgresql中提取电子邮件最后一个 '@'字符之前的部分?

macos - Bash + 替换列中的字符串/值

Javascript Regex - 替换所有出现的匹配字符串,除了括号之间的任何字符串