Masking credit card number
What is the best way to mask credit card number in PHP?
The credit card number doesn't have to be valid. So no need to do a Luhn Algorithm. As long as it matches the pattern replace it with XXXXXXXX.
What I have so far:
<?php
$str = "The quick brown fox jumps over 5192696222257727 dog.";
$credit_card_re = '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|622((12[6-9]|1[3-9][0-9])|([2-8][0-9][0-9])|(9(([0-1][0-9])|(2[0-5]))))[0-9]{10}|64[4-9][0-9]{13}|65[开发者_StackOverflow中文版0-9]{14}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})*$/';
$cc = "6789765435678765";
$cc = str_pad(substr($cc, -4), strlen($cc), '*', STR_PAD_LEFT);
Regular expressions will work fine, so what you have is good.
To actually do the regex, use this code:
$str = "The quick brown fox jumps over 5192696222257727 dog.";
$masked = preg_replace("/(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})/", "XXXXXXXX", $str);
Then you can do whatever with $masked
.
EDIT: Fixed the regex, yours only matches it if the entire string is the number.
A no regex solution, that works for any length string, to show only last 4:
function mask_cc( $number ) {
return substr_replace($number, str_repeat('X', strlen( $number ) - 4), 0, strlen( $number ) - 4);
}
http://www.php.net/manual/en/function.preg-replace.php
<?php
$str = "The quick brown fox jumps over 5192696222257727 dog.";
$pattern = '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|622((12[6-9]|1[3-9][0-9])|([2-8][0-9][0-9])|(9(([0-1][0-9])|(2[0-5]))))[0-9]{10}|64[4-9][0-9]{13}|65[0-9]{14}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})*$/';
$str = preg_replace($pattern , 'XXXXXXXX' , $str);
? Or don't I understand you?
<?php
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;
}
?>
Look here
精彩评论