Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to mask part of a string with asterisks

Short answer

substr_replace() replaces part of a string by position:

<?php
 
echo substr_replace('4276123456789012', str_repeat('*', 8), 4, 8);

Output:

4276********9012

The last four digits only

Keep the end of the string and pad it on the left:

<?php
 
$card = '4276123456789012';
 
echo str_repeat('*', strlen($card) - 4) . substr($card, -4);

Output:

************9012

An email address

Hide the name, keeping the first letter and the domain:

<?php
 
$email = 'anna.smith@example.com';
$name = strstr($email, '@', true);
 
echo $name[0] . str_repeat('*', strlen($name) - 1) . strstr($email, '@');

Output:

a*********@example.com

Functions used in this recipe

  • substr_replace — Replaces part of a string by position.
  • str_repeat — Repeats a string a given number of times.
  • strstr — Returns the part of a string starting at the first occurrence of a substring.

Thanks for reading!

Donate to the site — we work hard for you.