phpyk
9/13/2018 - 9:05 AM

字符串用*替换(脱敏)

/** * 只保留字符串首尾字符,隐藏中间用*代替(两个字符时只显示第一个) * @param string $user_name 姓名 * @return string 格式化后的姓名 */


    public static function substrCut($user_name)
    {
        $strlen = (int)mb_strlen($user_name, 'utf-8');
        $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
        $lastStr = mb_substr($user_name, -1, 1, 'utf-8');
        if ($strlen == 1) {
            return $user_name;
        } elseif ($strlen == 2) {
            return $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1);
        } else {
            return $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
        }
    }