This function will allow you to mask a string in PHP. A common use for this would be masking a credit card number and its sensitive PAN (primary account number) which is required for PCI DSS compliance. However, this function is not limited to this, it could be used to mask other sensitive data such as a SSN (social security number), accounting data, PII (personal identifiable information), or top secret data.

This PHP masking function allows you to set a variable number of characters to mask either starting from the beginning or the end. The default options mask all but the last 4 characters, which is typically used for credit cards and complying with PCI DSS. You can also set your masking character, by default it will use XXXXXXXXXXXX, but it could easily be changed to any other character such as an asterisk.

 * Places a mask on a string, useful for credit cards or other sensitive data that must be filtered
 * @param string $string The string that needs to be masked
 * @param string $maskChar The character used for masking
 * @param int $unmaskAmount The number of characters that should remain unmasked
 * @param bool $maskFromEnd If true masking should start from the end of the string instead of the beginning
 * @return string
function maskString($string, $maskChar = 'X', $unmaskAmount = 4, $maskFromEnd = false): string
    $maskLength = strlen($string) - $unmaskAmount;
    return substr_replace($string, str_repeat($maskChar, $maskLength), $maskFromEnd ? -$maskLength : 0, $maskLength);

This code snippet was published on It was last edited on



  • Votes
  • Oldest
  • Latest