I thought of working very simply using the substr_replace
function combined with strpos
.
See:
$mail = '[email protected]'
substr_replace($mail, '*****', 1, strpos($mail, '@') - 2);
The result is
'w*****[email protected]'
The explanation of the code is as follows: The third argument ( 1
) causes the position to be replaced to be from the first character. The fourth argument strpos($mail, '@')
will give us the final position where it should be replaced, which is @
. In this case, I used -2
so that neither the @
nor the last character before it was replaced.
Replacement size will be determined from the starting position. If it were necessary to display 2 characters at the beginning and 2 before the @
, we would have to change the function as follows:
substr_replace($mail, '*****', 2, strpos($mail, '@') - 4);