No need to regex, just go through the string and swap the letters for asterisks. When you find something that is not letter, stop:
for ($i = 0; $i < strlen($email); $i++) {
if (ctype_lower($email[$i]))
$email[$i] = '*';
else break;
}
echo $email;
I used ctype_lower
which checks if it’s a lowercase letter. If it is, I change it to an asterisk, and if it’s not I interrupt the loop.
But if you really want to use regex:
function troca($m) {
return str_repeat('*', strlen($m[1])). $m[2];
}
$email="[email protected]";
$emailRegex=preg_replace_callback('/^([a-z]+)(\d*@.+)$/', 'troca', $email);
echo $emailRegex;
I create 2 capture groups (indicated by the parentheses): one with the beginning letters and the other containing the numbers on. I use \d*
to indicate zero or more digits (in case you don’t have any), then the @
, and .+
(one or more characters) to go to the end of the string. I also use the markers ^
and $
, which indicate respectively the start and end of the string.
Then I create a substitution function, which takes the first group, checks the size and generates another string of the same size, but containing only asterisks - is what str_repeat
makes. Then I concatenate with the second group, which contains the rest of the string.
The difference is that to use the function I must use preg_replace_callback
instead of preg_replace
.
Particularly I prefer the first option. Regex even works but it seems to me unnecessarily complicated for your case.
Remembering that no solution validates if the string is in fact an email.