Replace all characters of a string with asterisks except for the last four characters

13.2k Views Asked by At

I want to mask the leading digits of a phone number using asterisks.

So that a message can be presented as:

Your phone number ********8898 has been sent with a verification code.
7

There are 7 best solutions below

2
On BEST ANSWER

If you wanna mask middle part:

private function stringToSecret(string $string = NULL)
{
    if (!$string) {
        return NULL;
    }
    $length = strlen($string);
    $visibleCount = (int) round($length / 4);
    $hiddenCount = $length - ($visibleCount * 2);
    return substr($string, 0, $visibleCount) . str_repeat('*', $hiddenCount) . substr($string, ($visibleCount * -1), $visibleCount);
}

Result:

  • 1 => 1
  • 12 => 12
  • 123 => 1*3
  • 1234 => 1**4
  • 12345 => 1***5
  • 123456 => 12**56
  • 1234567 => 12***67
  • 12345678 => 12****78
  • ...
1
On

Try this

$phone_number = '******' . substr( $phone_number, - 4);
echo $phone_number;
1
On

you can use substr :

 $my_text = '12345678';

echo substr($my_text, 1);  // 2345678
0
On
*******echo substr("9876543210", 6, 4);
0
On

If phonenumber length is more than 4, then you can do this:

substr_replace($number, str_repeat('*', strlen($number)-4), 0, -4);

If you want to also show the first digit:

substr_replace($number, str_repeat('*', strlen($number)-5), 1, -4);
3
On
$email_new = $email_new[0].$email_new[1].$email_new[2].$email_new[3].'******' . substr( $email_new, - 7);
0
On

Using preg_replace() will allow you to redact all except the last four characters of a string with an unknown length. This can be suitable as a utility function for all manner of values like phone numbers, credit card numbers, social security numbers, etc. Match any character which is followed by at least 4 characters and replace it with *. Redacting a portion of an email address can be a bit more convoluted.

Code: (Demo)

$phone = '040783248898';    
echo preg_replace('/.(?=.{4})/', '*', $phone);
// ********8898

If you actually need to find the 12-digit phone number in the string, then find match the leading 8 digits and look ahead for the remaining 4 digits, then replace the leading 8 digits with 8 asterisks. Demo

$msg = 'Your phone number 040783248898 has been sent with a verification code.';

echo preg_replace('/\b\d{8}(?=\d{4}\b)/', '********', $msg);
// Your phone number ********8898 has been sent with a verification code.