Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Mask part of a string in Laravel 8.x

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]
Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?