很簡單的功能,就安全上的理由,主要是把字串的中間部分加上 '*'。
第二個變數 $masknum 如果是負的,代表要留言不 MASK 的個數。
補充:此函數不處理中文字,輸入字串須大於2個字元才會加遮罩。
/**
* function MaskString(): Mask a string for security.
* @scope public
* @param string $s : input string, >2 characters long string
* @param interger $masknum : the number of characters in the middle of a string to be masked,
if masknum is negative, the returned string will leave abs(masknum) characters in
both end untouched.
* @return a masked string
* ex. MaskString( "12345678",3) : 123***78
* ex. MaskString( "12345678",-3) : 12*****8
*/
function MaskString($s, $masknum=3){
$len= strlen($s);
if($masknum<0) $masknum = $len + $masknum;
if($len<3)return $s;
elseif( $len< $masknum+1)return substr( $s, 0,1). str_repeat('*',$len-2). substr( $s, -1);
$right= ($len-$masknum)>>1;
$left= $len- $right- $masknum;
return substr( $s, 0,$left). str_repeat('*',$len-$right-$left). substr( $s, -$right);
}
原文 2011-05-14 16:31:54
