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.
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.
If you wanna mask middle part:
Result: