使用PHP检查电子邮件

I'm using this simple code:

$raw = 'text hi@li.com text';
$raw = preg_replace('<[\w.]+@[\w.]+>', '***@$2', $raw);

And i should get as output, something like ***@li.com; while i get ***@

I can't debug it, i don't know how what's wrong.


So the solution is

preg_replace('<([\w.]+)@([\w.]+)>', '***@$2', $raw);

I had to add () to make a group.

you need to create a group by adding (), and BTW it's gonna be $1:

$raw = ' hi@li.com ';
$raw = preg_replace('/[^@]+@([^\s]+)/', '***@$1', $raw);

also modified .+ tp [^\s]+ so it "eats" only the email and not the text after it

$raw = ' hi@li.com ';
$raw = preg_replace('/[^@]+@(.+)/', '***@$1', $raw);

Here without regex:

$raw = 'hi@li.com';
$raw = explode('@', $raw);
array_shift($raw);
$raw = '***@'.implode('', $raw);

Regex is a little bit overkill for this task. Using the explode() function and a little bit of string concatenation would should be enough.

$pieces = explode('@', $raw);
$raw = '***@' . $raw[count($raw) - 1];

Notice, the way I'm accessing the domain part of the email address stored in $raw. I'm not using $raw[1] because the @ character can actually be used as an email address (If it's surrounded by quotation marks), although it is a bit unusual actually. You can see some more example of email addresses here: http://en.wikipedia.org/wiki/Email_address#Valid_email_addresses

You could alternatively use the strstr() function. Also with the true param you can get the part before the needle and count the length and pad with asterix.

<?php
$email  = 'name@example.com';

$len = strlen(strstr($email, '@', true));
$domain = strstr($email, '@');

echo str_repeat('*',$len).$domain; // prints ****@example.com
?>