cedivad
cedivad

Reputation: 2644

Censor emails with PHP

I'm using this simple code:

$raw = 'text [email protected] 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.

Upvotes: 1

Views: 1698

Answers (5)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

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  = '[email protected]';

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

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

Upvotes: 0

Fad
Fad

Reputation: 9858

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

Upvotes: 0

Gavriel
Gavriel

Reputation: 19237

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

$raw = ' [email protected] ';
$raw = preg_replace('/[^@]+@([^\s]+)/', '***@$1', $raw);

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

Upvotes: 3

dan-lee
dan-lee

Reputation: 14492

Here without regex:

$raw = '[email protected]';
$raw = explode('@', $raw);
array_shift($raw);
$raw = '***@'.implode('', $raw);

Upvotes: 1

aefxx
aefxx

Reputation: 25249

$raw = ' [email protected] ';
$raw = preg_replace('/[^@]+@(.+)/', '***@$1', $raw);

Upvotes: 3

Related Questions