Skip to content

Instantly share code, notes, and snippets.

@kristos80
Last active November 23, 2023 13:01
Show Gist options
  • Save kristos80/03a5189fc524697a8cac385afe366046 to your computer and use it in GitHub Desktop.
Save kristos80/03a5189fc524697a8cac385afe366046 to your computer and use it in GitHub Desktop.
Generic utility method in PHP to mask a string with a specific character. Can be used for password masking eg
<?php
/**
* Generic utility method to mask a string with a specific character
*
* @param string $stringToMask The string to be masked
* @param int $percentageOfCharactersToShow What percentage of characters to show. Default = 20%
* @param string $maskCharacter With which character to mask. Default = '*'. If more characters are used, only the first will be used as mask
* @param bool $maskFromStart From which direction to start masking. TRUE = From start, FALSE = From the end
* @return string
*/
function maskString(string $stringToMask,
int $percentageOfCharactersToShow = 20,
string $maskCharacter = "*",
bool $maskFromStart = TRUE): string {
if(in_array($len = strlen($stringToMask),
[
0,
1,
2,
])) {
return $len ? str_repeat("*", $len) : "";
}
$maskCharacter = strlen($maskCharacter) ? substr($maskCharacter, 0, 1) : "";
$percentageOfCharactersToShow < 1 || $percentageOfCharactersToShow > 50 && ($percentageOfCharactersToShow = 50);
$howManyCharactersToKeep = (int) floor($len * $percentageOfCharactersToShow / 100);
!$howManyCharactersToKeep && ($howManyCharactersToKeep = 1);
$charsToKeep =
substr($stringToMask, $maskFromStart ? $howManyCharactersToKeep * -1 : 0, $howManyCharactersToKeep) ?: "";
$maskedString = str_repeat($maskCharacter, $len - $howManyCharactersToKeep);
return $maskFromStart ? "$maskedString$charsToKeep" : "$charsToKeep$maskedString";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment