PHP - 在字符串中搜索不同的电子邮件地址变体

时间:2014-12-24 12:56:19

标签: php preg-replace

我正在尝试弄清楚如何使用PHP preg_replace替换字符串中的电子邮件地址(电子邮件隐藏)。我正在构建一个应用程序,我不希望客户发布他们的联系信息。通过使用以下内容,大多数人开始变得聪明:

james(at)yahoo dot com

james at example dot com

如何阻止这种情况发生?

如何将其添加到此:

$emailHidden = 'james at example dot com';

$emailHidden = 'james (at) example dot com';

$emailHidden = 'james at example.com';

$emailHidden = preg_replace('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i','(email hidden)',$emailHidden); // extract email

此外,我仍想删除常规电子邮件地址。例如james@yahoo.com

2 个答案:

答案 0 :(得分:1)

我认为你在寻找的是:

$emailHidden = 'james at example dot com';
$emailHidden = 'james (at) example dot com';
$emailHidden = 'james at example.com';

$emailHidden = preg_replace('/[[A-Z0-9._%+-]+[ ]?[\(]?(@|at)[\)]?[ ]?[A-Z0-9.-]+[ ]?[\(]?(\.|dot)[)]?[ ]?[A-Z]{2,4}/i','(email hidden)',$emailHidden); // extract email

将捕获:

james at google dot com
 james@google.com
 詹姆斯@谷歌(点)的COM
 jogle at google.com
 james(at)google(dot)com

答案 1 :(得分:-1)

如果您想将常规电子邮件替换为其他格式,可以尝试此操作。

$email = 'somebody@anywhere.com';
$newEmail = preg_replace('/([A-Z0-9._%+-]+)@([A-Z0-9.-]+\.[A-Z]{2,4})/i', ' $1 (at) $2', $email);
echo $newEmail;

输出是:

somebody (at) anywhere.com

或者如果你想抓住其他人,那么你可以使用这些正则表达式:

$email = 'james at example dot com';
$emailHidden = preg_replace('/[A-Z0-9._%+-]+[^\s] at [A-Z0-9.-]+[^\s] dot [A-Z]{2,4}/i', 'hidden email', $email);

$email = 'james (at) example dot com';
$emailHidden = preg_replace('/[A-Z0-9._%+-]+[^\s] \(at\) [A-Z0-9.-]+[^\s] dot [A-Z]{2,4}/i', 'hidden email', $email);

$email = 'james at example.com';
$emailHidden = preg_replace('/[A-Z0-9._%+-]+[^\s] at [A-Z0-9.-]+\.[A-Z]{2,4}/i', 'hidden email', $email);