我正在尝试创建一个函数,将给定字符串中每次出现的纯文本电子邮件地址转换为它的htmlized 版本。
假设我有以下代码,其中 htmlizeEmails
是我正在寻找的函数:
$str = "Send me an email to bob@example.com.";
echo htmlizeEmails($str); // Echoes "Send me an email to <a href="mailto:bob@example.com">bob@example.com</a>."
如果可能的话,我希望这个函数使用 filter_var
函数来检查电子邮件是否有效。
有人知道怎么做吗?谢谢!
编辑:
感谢您的回答,我使用 Shocker 的正则表达式来匹配潜在的电子邮件地址,然后,仅如果 filter_var
验证它,它就会被替换。
function htmlizeEmails($text)
preg_match_all('/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})/', $text, $potentialEmails, PREG_SET_ORDER);
$potentialEmailsCount = count($potentialEmails);
for ($i = 0; $i < $potentialEmailsCount; $i++) {
if (filter_var($potentialEmails[$i][0], FILTER_VALIDATE_EMAIL)) {
$text = str_replace($potentialEmails[$i][0], '<a href="mailto:' . $potentialEmails[$i][0] .'">' . $potentialEmails[$i][0] .'</a>', $text);
}
}
}
最佳答案
$str = preg_replace('/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})/', '<a href="mailto:$1">$1</a>', $str);
其中([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6} )
是用于检测电子邮件地址的正则表达式(这是一个通用示例,电子邮件地址可能比这更复杂,可能不会涵盖所有地址,但是找到完美的电子邮件正则表达式取决于您)
关于php - 检测文本中的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9763606/