Solution 1: Universal Approach
You can mask the first and last few characters of a string without using extra functions.
Example with a loop:
$string = "123456789";
$i = 0;
$limit = 3;
while (isset($string[$i])) {
if ($i < $limit) {
$string[$i] = '*'; // mask first 3 characters
}
$i++;
}
// mask last 3 characters
$string[$i - 1] = '*';
$string[$i - 2] = '*';
$string[$i - 3] = '*';
echo $string; // ***456***
PHP 7.1+ (using negative string indexes):
From PHP 7.1 onward, you can simplify masking the first and last characters:
$string = "123456789";
$string[0] = $string[1] = $string[2] = '*'; // first 3 chars
$string[-1] = $string[-2] = $string[-3] = '*'; // last 3 chars
echo $string; // ***456***
Solution without functions (may trigger a PHP Notice):
This version avoids using any string functions, but can produce a notice when the end of the string is reached. You can suppress it with @:
$string = "123456789";
$i = 0;
$limit = 3;
while (true) {
if ($string[$i] == '') {
break; // end of string
}
if ($i < $limit) {
$string[$i] = '*'; // mask first 3 chars
}
$i++;
}
// mask last 3 characters
$string[$i - 1] = '*';
$string[$i - 2] = '*';
$string[$i - 3] = '*';
echo $string; // ***456***
This way, you can control how many characters at the start and end you want to mask, and it works even without external functions.