regexp to partly hide email? [closed]

2020-05-03 11:36发布

问题:

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 7 years ago.

It's rather simple what I'm trying to achieve, I want input such as

漢aelena@tratata.com

to be:

漢******@tratata.com

So I made this regexp to match between the first char and the '@'.

mb_regex_encoding ('UTF-8' );
mb_ereg_replace('(?<=^.{1}).*?(?=@)','*','漢aelena@tratata.com',1);

The problem though, it would only match it one time, and thus would only put in there one star, instead of six. Something like this, is what I would get:

漢*@tratata.com

Then I wanted to use mb_ereg_replace_callback, to return:

return $matches[1].str_repeat('*', strlen($matches[1]));

Then I read specs and it said mb_ereg_replace_callback is available in PHP 5.4.1 or later.

...Any ideas how could I achieve the same thing?

回答1:

There is no need to use a callback function, a single regular expression can do it.

(?<=.).(?=.*@)
  • (?<=.), make sure there is at least one character before so it won't replace the first character.
  • ., match any character.
  • (?=.*@), make sure there is a @ somewhere after the character.

Example with function changed to preg_replace with unicode modifier (as suggested):

echo preg_replace('/(?<=.).(?=.*@)/u','*','漢aelena@tratata.com');

Outputs:

漢******@tratata.com


回答2:

You could use the preg_replace_callback() function from the PCRE family. You can use the u modifier to support UTF-8.

Please note there are some smaller differences between the PCRE (preg_) and POSIX (ereg_) way, besides that the latter is deprecated.



回答3:

<?php

$email = '漢aelena@tratata.com';

    $email = preg_replace_callback('#^(.){1}(.*?)@#u', function($matches)
            {
                return $matches[1] . str_repeat('*', mb_strlen($matches[2])) . '@';
            },
    $email);

echo $email; # 漢******@tratata.com


回答4:

A replacement callback is an option.

echo preg_replace_callback('/(?<=^.).+(?=@)/u', function($match) {
    return str_pad('', strlen($match[0]), '*');
}, "something@something.com");
//s*******@something.com

Note I use an anonymous function as the callback - this is PHP >= 5.3 only. If you're on < 5.3, use a named function or one created with function_create().



回答5:

Why use regexp at all when this can be done much faster?

if(($pos = mb_strpos($email,'@')) > 0) {
    for($i=1;$i<=$pos;$i++) {
        $email[$i] = '*';
    }
}