Swap the letters of the beginning of an email with another character

Asked

Viewed 191 times

-1

I’m trying to replace letters with asterisks of an email using the preg_replace() php, but php takes all the letters in the email, but I just want to put the asterisks in the first letters. example:

input: [email protected] exit: *********[email protected]

But my code is taking all the letters and replacing them with asterisks for example: input: [email protected]
exit: *********2020@*****.***

my code:

<?php 
    $email="[email protected]";

    $emailRegex=preg_replace('/([a-z])/','*', $email);
    
    echo $email;
    echo "<br>";
    echo $emailRegex;

1 answer

1


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.