replace() and mask()
Replace parts of a string, or mask sensitive characters.
Syntax
\Illuminate\Support\Str::mask($string, '*', 4);The Str::replace() method swaps one substring for another. The Str::mask() method hides a portion of a string with a repeated character — handy for showing partial emails or card numbers.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A template engine replaces {{name}} and {{amount}} placeholders in an email body with actual values using Str::replace().
- A compliance module masks the middle digits of credit card numbers stored in log files using Str::mask() before writing them to disk.
- A migration script replaces an old domain name throughout a batch of user-generated HTML strings with the new domain using Str::replace().
More examples
Replace a substring
Replaces an array of search strings with their corresponding replacement values in a single call.
use Illuminate\Support\Str;
$template = 'Hello, {{name}}! Your balance is {{amount}}';
$message = Str::replace(
['{{name}}', '{{amount}}'],
['Alice', '$250.00'],
$template
);
// => 'Hello, Alice! Your balance is $250.00'Case-insensitive replace
Str::replaceFirst() swaps only the first matching occurrence, useful when subsequent occurrences must be handled separately.
use Illuminate\Support\Str;
$text = 'Visit HTTP://EXAMPLE.COM or http://example.com';
$fixed = Str::replaceFirst('HTTP://EXAMPLE.COM', 'https://example.com', $text);
// replaceFirst replaces only the first occurrenceMask sensitive data with Str::mask()
Str::mask() replaces a range of characters with a repeating mask character, ideal for hiding credit card numbers and email addresses in logs.
use Illuminate\Support\Str;
$card = '4111111111111234';
$masked = Str::mask($card, '*', 0, 12);
// => '************1234'
$email = '[email protected]';
$maskedE = Str::mask($email, '*', 2, 5);
// => 'al*****xample.com'
Discussion