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: