Mask part of a string in Laravel 8.x – Amit Merchant – A blog on PHP, JavaScript, and more

Related Articles

There comes a time when you will have to blur a certain part of the string. For example, to obscure the credit card digits except for the last four or disguise specific parts of the phone or email number.

The best way to make a mist / mask is by replacing the intended part of the string with stars.

In the latest release of Laravel 8.x, a method called mask() Added to the framework that allows you to do just that.

So, according to PR, This method mask() Allows you to disguise a part of a string with a repeating character like this.

use IlluminateSupportStr;

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

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

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

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

As you may know, e mask() The method accepts the string to disguise as its first parameter, the character by which you want to disguise it as a second parameter, and the other parameters allow you to specify the part of the string to be disguised.

The method accepts quite a few more parameters besides what I mentioned above. This is what the signature of the method 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(
    $length = null, 
    $encoding = 'UTF-8'

So, by matching $index And $length Parameters, you can even use a negative index with such a custom length.

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

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

Here are some more examples of using the method for different use cases I took from the method Tests.



Please enter your comment!
Please enter your name here

Popular Articles