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********9012The 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:
************9012An 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.comFunctions 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.