Current Location: Home> Latest Articles> Practical PHP Tutorial: Easily Hide the Middle Four Digits of a Phone Number to Protect Privacy

Practical PHP Tutorial: Easily Hide the Middle Four Digits of a Phone Number to Protect Privacy

M66 2025-07-10

The Importance of Protecting User Privacy by Masking the Middle Four Digits of Phone Numbers

In practical development, protecting privacy when handling users' phone numbers is essential. Displaying full phone numbers publicly can lead to privacy breaches and security risks. Therefore, it is common to mask part of the phone number, especially the middle four digits.

PHP Example Code to Hide the Middle Four Digits of a Phone Number

<?php
function hidePhoneNumber($phone) {
    $length = strlen($phone);
    $start = substr($phone, 0, 3);
    $end = substr($phone, -4);
    $hidden = str_pad('', $length - 7, '*');
    
    return $start . $hidden . $end;
}

$phoneNumber = '13812345678';
$hiddenPhoneNumber = hidePhoneNumber($phoneNumber);
echo $hiddenPhoneNumber;
?>

The code above defines a function called hidePhoneNumber. It takes a phone number string as input, obtains the length of the number, extracts the first three and last four digits, replaces the middle part with asterisks (*), and returns the masked phone number.

Effect of the Code and Usage Scenarios

Using the example phone number '13812345678' as input, the output will be 138****5678, successfully masking the middle four digits. This method is simple and efficient, suitable for displaying user information and protecting data in various scenarios.

Additional Recommendations: Combine with Security Measures to Enhance Privacy Protection

Besides masking the display, developers should also adopt measures such as data encryption, secure transmission protocols (like HTTPS), and access control to comprehensively protect user information and improve overall system security.

Summary

With the PHP code example provided, you can easily mask the middle four digits of phone numbers to effectively protect user privacy. We hope this tutorial offers practical assistance for your project development.