Skip to content
Advertisement

Censor emails with 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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement