接到一个中间N位打码需求,百度了下没找到有啥轮子可以拿来用,写了个方法在此记录
希望可以帮到大家 复制改一改就可以用了 欢迎各路大神帮忙改进和指导
/**
* 敏感数据打码(有可能是手机号、身份证等)
* @param string $data 敏感字符串
* @param int $hideNum 打码数字(中间n位)
*
* @return string 打码后的数据
*/
public function hideSensitiveData($data, $hideNum = 5)
{
// 获取字符串长度
$strLen = strlen($data);
// 获取中间个数
$midLen = floor($strLen/2);
// 获取起始位置
$startLen = $midLen-(floor($hideNum/2));
// 查看是否够隐藏个数 不够就按长度全部打*
if ($hideNum <= $strLen)
{
$data = substr_replace($data, str_repeat('*', $hideNum), $startLen, $hideNum);
} else {
$data = str_repeat('*', $strLen);
}
return $data;
}