Obscuring Parts of a String

Learn how to obscure parts of a string with the help of examples.

The mask helper method

It is a simple but handy string manipulation method. We can use this method to hide or obscure parts of an existing string.

Press + to interact
<?php
/**
* Versions: Laravel 8, 9
*
* @return string
*/
public static function mask(
string $string,
string $character,
int $index,
int|null $length = null,
string $encoding = 'UTF-8'
);

One of the most common applications of this helper method is to only store and display the last four digits of a credit card number:

Press + to interact
<?php
use Illuminate\Support\Str;
// Returns "************4242"
Str::mask(
'4242424242424242',
'*',
0, -4
);

In the previous example, we are using several ...