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.
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.
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);
$email_new = $email_new[0].$email_new[1].$email_new[2].$email_new[3].'******' . substr( $email_new, - 7);
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.
If you wanna mask middle part:
Result: