Friday, October 5, 2007

[PHP] masking a credit card number

So if you have ever had to create a shopping cart and on the receipt page you want to display the last 4 digits of the credit card number and just x out the rest well you would prolly create a bit of code like on the php.net comments such as:
function mask ( $str, $start = 0, $length = null ) {
$mask = preg_replace ( "/\S/", "*", $str );
if ( is_null ( $length )) {
$mask = substr ( $mask, $start );
$str = substr_replace ( $str, $mask, $start );
} else {
$mask = substr ( $mask, $start, $length );
$str = substr_replace ( $str, $mask, $start, $length );
}
return $str;
}

But of course I don't like that solutions so here is my version:
$maskedCcn = substr_replace(
preg_replace( '/\S/', 'X',
preg_replace( '/[^0-9]*/', null, $cardNumber );
),
substr( $maskedCcn, -4 ),
strlen( $maskedCcn ) - 4,
4
);

2 comments:

eller said...

HELP! I'm trying to use your PHP code but all I get in the result is the credit card number with the last 4 digits cut off. No Xs display, I see the cc numbers without the last 4. I think I've copied your code exactly with the exception of the first ;. (I get an error with the first ; in place.) Here is the code as I've entered it:

$maskedCcn = substr_replace (preg_replace('/ \S/', 'X', preg_replace( '/[^0-9]*/', null, $FTGCard_Number)), substr( $maskedCcn, -4), strlen( $maskedCcn) - 4, 4 );


Is there something missing from my code?

Cody said...

Nice, clean workaround.