How can I get the length of a string and replace the first and last three characters in PHP without using a custom function?

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.

Solution 2: Masking Without Built-in String Functions

Even if you prefer not to use PHP string functions, you can still determine the string length manually and mask the first and last 3 characters:


<?php
function privacy($string) {
    // Get the string length manually
    $i = 0;
    while ($string[$i] !== "") {
        $i++;
    }

    // Replace the first and last 3 characters with '*'
    // Only if the string length is 6 or more
    if ($i >= 6) {
        for ($x = 0; $x < 3; $x++) {
            $string[$x]      = "*";       // first 3 chars
            $string[$i - $x] = "*";       // last 3 chars
        }
    }

    return $i . "<br>" . $string;
}

echo privacy("123456789");