开发者

masking credit card & bank account information

I'm looking for a php function which can mask credit card & bank information such as routing number and account numbers. I need to mask many formats, so the existing stack overflow answers don开发者_如何转开发't help me that much.

So for example, if the input is 304-443-2456, the function should return xxx-xxx-2456. Sometimes the number has dashes, and can be in various lengths.

I'm looking for something generic, that I can extend as needed, preferably a zend framework view helper class.


Some little regex in a function of it own, configuration available:

$number = '304-443-2456';

function mask_number($number, $count = 4, $seperators = '-')
{
    $masked = preg_replace('/\d/', 'x', $number);
    $last = preg_match(sprintf('/([%s]?\d){%d}$/', preg_quote($seperators),  $count), $number, $matches);
    if ($last) {
        list($clean) = $matches;
        $masked = substr($masked, 0, -strlen($clean)) . $clean;
    }
    return $masked;
}

echo mask_number($number); # xxx-xxx-2456

If the function fails, it will return all masked (e.g. a different seperator, less than 4 digits etc.). Some child-safety build in you could say.

Demo


<?php

function ccmask($cc, $char = '#') {
    $pattern = '/^([0-9-]+)([0-9]*)$/U';
    $matches = array();
    preg_match($pattern, $cc, $matches);
    return preg_replace('([0-9])', $char, $matches[1]).$matches[2];
}

echo ccmask('304-443-2456'), "\n";  
echo ccmask('4924-7921-9900-9876', '*'), "\n";  
echo ccmask('30-43-56', 'x'), "\n";  

Outputs:

###-###-2456
****-****-****-9876
xx-xx-56


I use a view helper for that. I tend to avoid Regex though as it always takes me ages to work out what it does, especially if I come back to code after a while.

class Zend_View_Helper_Ccmask
{
    public function ccmask($ccNum)
    {
        $maskArray = explode('-', $ccNum);
        $sections = count($maskArray) - 1;
        for($i = 0; $i < $sections ; $i++){
            $maskArray[$i] = str_replace(array(1,2,3,4,5,6,7,8,9,0), 'x', $maskArray[$i]);
        }
        return implode('-', $maskArray);
    }
}

In your view

echo $this->ccmask('304-443-2456');
//output = xxx-xxx-2456


A good way to look at this is at what won't be masked and outputing xs for everything else. A simple, inexpensive solution is:

function cc_mask( $cc_raw, $unmask_count ){
 $cc_masked = '';
 for( $i=0; $i < ( strlen( $cc_raw ) - $unmask_count ) ; $i++ ){
  //If you want to maintain hyphens and special characters
  $char = substr( $cc_raw, $i, 1 );
  $cc_masked .= ctype_digit( $char ) ? "*" : $char;
 }
$cc_masked .= substr( $cc_raw ,  -$unmask_count );
 return $cc_masked;

}

echo cc_mask("304-443-2456",4);

//Output
***-***-2456

Would be even faster if there was no need to maintain the hyphens and special characters

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜