Search code examples
phpstringphone-numberdata-maskingredaction

Replace all characters of a string with asterisks except for the last four characters


I want to mask the leading digits of a phone number using asterisks.

So that a message can be presented as:

Your phone number ********8898 has been sent with a verification code.

Solution

  • If you wanna mask middle part:

    private function stringToSecret(string $string = NULL)
    {
        if (!$string) {
            return NULL;
        }
        $length = strlen($string);
        $visibleCount = (int) round($length / 4);
        $hiddenCount = $length - ($visibleCount * 2);
        return substr($string, 0, $visibleCount) . str_repeat('*', $hiddenCount) . substr($string, ($visibleCount * -1), $visibleCount);
    }
    

    Result:

    • 1 => 1
    • 12 => 12
    • 123 => 1*3
    • 1234 => 1**4
    • 12345 => 1***5
    • 123456 => 12**56
    • 1234567 => 12***67
    • 12345678 => 12****78
    • ...