Current Location: Home> Latest Articles> How to Achieve One-Click Data Masking for Sensitive Information like ID Numbers and Phone Numbers Using mb_eregi_replace?

How to Achieve One-Click Data Masking for Sensitive Information like ID Numbers and Phone Numbers Using mb_eregi_replace?

M66 2025-06-29

In the actual development process, handling sensitive information such as ID numbers and phone numbers is an essential part of privacy protection. When displaying these pieces of information, we aim to mask part of the sensitive content to prevent the leakage of user privacy. This article will introduce how to use the PHP function mb_eregi_replace to achieve one-click data masking.


What is mb_eregi_replace?

mb_eregi_replace is a multibyte string function in PHP, used for case-insensitive regular expression replacements within a string. It supports multibyte encodings like UTF-8, making it especially suitable for processing Chinese characters and other multibyte characters.


Basic Approach to Data Masking

Taking phone numbers and ID numbers as examples, common methods of data masking include:

  • Phone Number: Mask the middle four digits, e.g., 13812345678 becomes 138****5678.

  • ID Number: Mask the middle 10 digits, e.g., 110105199001011234 becomes 1101**********1234.


Sample Code

Below is a PHP code example for implementing data masking using mb_eregi_replace:

<?php
// Mask phone number
function mask_mobile($mobile) {
    // Match phone number format, replace the middle 4 digits with ****
    return mb_eregi_replace('(\d{3})\d{4}(\d{4})', '$1****$2', $mobile);
}
<p>// Mask ID card number<br>
function mask_idcard($idcard) {<br>
// Match ID card number, replace the middle 10 digits with **********<br>
return mb_eregi_replace('(\d{4})\d{10}(\d{4})', '$1**********$2', $idcard);<br>
}</p>
<p>// Test<br>
$mobile = '13812345678';<br>
$idcard = '110105199001011234';</p>
<p>echo "Original phone number: $mobile\n";<br>
echo "Masked phone number: " . mask_mobile($mobile) . "\n";</p>
<p>echo "Original ID card number: $idcard\n";<br>
echo "Masked ID card number: " . mask_idcard($idcard) . "\n";<br>
?><br>


Explanation

  • The regular expression (\d{3}) and (\d{4}) represent capturing groups for the numbers before and after the masked portion.

  • The replacement part uses $1 and $2 to reference the captured groups, keeping the first and last digits, while replacing the middle part with *.

  • mb_eregi_replace is case-insensitive and supports multibyte characters, making it suitable for processing text with various encodings.


Further Optimization

Depending on business requirements, similar masking can be applied to other sensitive information like email addresses or bank card numbers by simply adjusting the regular expression.


Reference Example Links

For more PHP string handling techniques, you can visit the following resource:

$url = 'https://m66.net/php-string-functions.html';
echo "For detailed tutorials, visit: $url";