In modern websites and applications, user privacy protection is crucial. Mobile numbers, as sensitive personal information, may lead to privacy risks if displayed directly. Therefore, a common practice is to mask the mobile number by replacing some of the digits with asterisks, thus protecting user privacy. This article will explain how to use the mb_eregi_replace function in PHP to mask mobile numbers.
mb_eregi_replace is a multibyte regular expression replacement function in PHP, supporting case-insensitive matching. It is particularly useful for handling strings that contain multibyte characters (such as Chinese). Compared to the regular preg_replace, it is more stable when dealing with multilingual content.
Function prototype:
string mb_eregi_replace ( string $pattern , string $replacement , string $string [, int $option = 0 ] )
$pattern: The regular expression (case-insensitive)
$replacement: The replacement content
$string: The input string
$option: An optional parameter, generally not used
A typical mobile number consists of 11 digits, such as: 13812345678. A common masking rule is to hide the middle 4 digits, for example: 138****5678.
<?php
// Example mobile number
$phone = "13812345678";
<p>// Use mb_eregi_replace to replace the middle 4 digits with asterisks<br>
$masked_phone = mb_eregi_replace('(\d{3})\d{4}(\d{4})', '$1****$2', $phone);</p>
<p>echo $masked_phone; // Output: 138****5678<br>
?><br>
The regular expression (\d{3})\d{4}(\d{4}) contains:
(\d{3}) captures the first 3 digits
\d{4} matches the middle 4 digits (but doesn't capture them)
(\d{4}) captures the last 4 digits
The replacement string $1****$2 means replacing the middle 4 digits with 4 asterisks, keeping the first and last digits.
This way, the mobile number is successfully masked.
Suppose a website page needs to display a user’s mobile number, but for privacy protection, it should be masked:
<?php
// Assume this is the user’s mobile number, usually fetched from the database
$user_phone = "13898765432";
<p>// Masking process<br>
$masked_phone = mb_eregi_replace('(\d{3})\d{4}(\d{4})', '$1****$2', $user_phone);</p>
<p>echo "User's Mobile Number: ".$masked_phone;<br>
?><br>
The output will be:
User's Mobile Number: 138****5432
Using PHP's built-in mb_eregi_replace function, you can easily perform regular expression replacement to mask mobile numbers and protect user privacy. This method is simple and efficient, suitable for multibyte encoding environments, and meets the needs of practical development.