Mask part of a string in Laravel 8.x

Amit Merchant · November 6, 2021 ·

There comes a time when you would be in need of obfuscating a certain part of the string. For instance, to obfuscate the credit card’s digits except the last four or to mask specific parts of the phone number or email.

The best way to do obfuscate/mask is by replacing the intended part of the string with the stars.

In the recent release of Laravel 8.x, a method called mask() is added to the framework that lets you do just that.

So, according to the PR, this method mask() lets you mask a portion of a string with a repeated character like so.

use Illuminate\Support\Str;

echo Str::mask('1234567891234567', '*', 0, 12);

// ************4567

Str::mask('[email protected]', '*', 3);

// my******************

As you can tell, the mask() method accepts the string to be masked as its first parameter, the character using which you want to mask it as a second parameter, and the rest of the parameters allows you to specify the part of the string to be masked.

The method accepts quite a few more parameters apart from what I have mentioned above. Here’s how the method signature looks like.

/**
 * Masks a portion of a string with a repeated character.
 *
 * @param  string  $string
 * @param  string  $character
 * @param  int  $index
 * @param  int|null  $length
 * @param  string  $encoding
 * @return string
 */
public static function mask(
    $string, 
    $character, 
    $index, 
    $length = null, 
    $encoding = 'UTF-8'
)

So, by tweaking the $index and the $length parameters, you can even use a negative index with a custom length like so.

echo Str::mask('+56 9 87654321', '*', -8, 6);

// + 56 9 ******21

Here are a few more examples of using the method for different use cases that I took from the method’s tests.

echo Str::mask('[email protected]', '*', -13);

// tay*************

echo Str::mask('[email protected]', '*', 16);

// [email protected]

echo Str::mask('[email protected]', '*', -99, 5);

// *****[email protected]

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?