Search⌘ K
AI Features

Obscuring Parts of a String

Explore how to apply Laravel's mask helper method to obscure parts of strings effectively. Understand the parameters for masking specific sections, learn best practices for handling sensitive data, and gain practical knowledge to securely display partial information such as API keys or credit card digits.

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.

PHP
<?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:

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

In the previous example, we are using several parameters. We indicate that the masking should start at the first character by ...