How to hide part of a string in Laravel
Overview
You can hide part of an email, phone number, or account details, which might look like +23490*******11. This is mostly done when the complete information or string poses a security trick. In this shot, we will learn how to use the mask() method to hide part of a string.
The mask() method
The mask() method is used to hide or replace all or parts of a string with a repeated character.
Syntax
$string = Str::mask('stringtohide', '*', -15, 3);
Parameter
The mask() method receives four parameters:
- The string to mask.
- The character to be used for masking. e.g.,
*. - The number that represents where you want to start masking from.
- The number that represents where you want to end masking at.
Example
use Illuminate\Support\Str;
$string = Str::mask('taylor@example.com', '*', 3, 5);
Explanation
From your controller, add the use Illuminate\Support\Str; class.
Then, paste the following code where you want to use the masking:
Str::mask('taylor@example.com', '*', 3, 5);
I use the Str facade as it is what Laravel provides to manipulate strings, and then call the mask() method.
The first parameter is the string we want to mask. The second parameter is the character we want to use to replace the strings we are masking; '*' or 'X' are commonly used. The third parameter is where we want to start masking from. In the example, we use 3, so we will start after the third character, i.e., we start replacing the characters of taylor@example.com after tay with *, and we replace five characters.
Output
tay*****xample.com