PHP Mask Credit Card Number

This method masks credit card numbers and shows only the last 4 digits. I also forgot where I got this method from. If you wish to change the number of last digits shown, just modify the last parameter of the method. The part where it says $l = 4.

function maskCC($n, $b = 4, $p = 16, $m = 'X', $l = 4) {
  // $n = 'card number: 1234567890123456' string
  // $b = break into how many in each chunk?
  // $p = pad to what length?
  // $m = mask character?
  // $l = leave how many numbers showing?
  preg_match("/card number:\s*(\d+)[^\d]*/i", trim($n), $matches);
  $pattern = "/card number:\s*(\d+)/ie";
  $replacement = " implode('-', str_split( substr_replace( str_pad('$1', '$p', '0', STR_PAD_LEFT), str_repeat('$m', $p-$l), 0, $l * -1 ), $b) ); ";
  return preg_replace($pattern, $replacement, trim($n));

// use the function
var_dump(maskCC("\ncard number: 1222233334444\n"));

Related Posts Plugin for WordPress, Blogger...


  1. Been reading for a few days now. It was very helpful and solid information. BTW, I like your site design as well. I enjoyed reading it and hopefully you will write more soon. Do you have a newsletter? How do I subscribe to the blog itself?

  2. preg_replace(‘/(?!^.?)[0-9](?!(.){0,3}$)/’, ‘*’, ‘3456-7890-1234-5678’)

    Keep the FIRST CHARACTER, the LAST CHARACTER, and any NON-NUMERIC CHARACTERS in-between. Everything else is masked (*).

    “3456-7890-1234-5678” = “3***-****-****-5678”
    “4567890123456789” = “4***********6789”
    “4928-abcd9012-3456” = “4***-abcd****-3456”
    “498291842” = “4****1842”

    If the regular expression is a bit confusing, (?!) is a “look-ahead not-equals”, meaning make sure this does NOT come next/before, but leave it alone.

Leave a Reply

Your email address will not be published. Required fields are marked *