php 手机加*星 【字符串】

场景:展示手机号时,避免暴露隐私信息,因此需要给手机号加*号

代码

php 复制代码
/**
 * 手机号码隐私加星
 * @param string $mobile 手机号
 */
function mobileToStar(string $mobile)
{   
    // 正则检测手机号
    if(!preg_match('/^1[3456789]\d{9}$/',$mobile)){
        // 手机格式错误
        return false;
    }
    // 粗暴法
    // $mobile[4] = "*";
    // $mobile[5] = "*";
    // $mobile[6] = "*";
    // $mobile[7] = "*";
    // return $mobile;
    
    // 截取替换法
    // $mobile_arr = str_split($mobile , 4); // 4个字符  1个字符串,切割 最后长度3
    // $mobile_arr[1] =  '****'; // 把中间4个用* 代替
    // return implode($mobile_arr);

    // 直接替换法
    // return substr_replace($mobile , '****' , 4,4);

    // 字符串截取法
    $start_str = substr($mobile , 0 , 4);// 从0位开始截取,取4个字符
    $in_str = str_pad('',4,'*'); // 设置 * 号
    $end_str = substr($mobile , 8 , 4); // 结束部分  从第8位开始截取,取4个
    return $start_str . $in_str. $end_str;
}

输出

php 复制代码
var_dump(mobileToStar('13112346458'));
// string(11) "1311****458"
相关推荐
Lhappy嘻嘻6 小时前
Java IO|File 文件操作 + 字节流 / 字符流完整笔记 + 递归删除文件实战
java·笔记·php
2601_963771378 小时前
How to Scale Your WordPress Store Traffic in 2026
前端·php·plugin
右耳朵猫AI12 小时前
PHP周刊2026W28 | 安全更新、Laravel 13.18、Twig 3.28
开发语言·php·laravel
罗政13 小时前
PDF 批量合并工具:本地 AI 自动排序、识别正文日期与合同编号
数据库·pdf·php
糖果店的幽灵14 小时前
安全测试从入门到精通_网络基础与HTTPS
网络·https·php
2601_9637713715 小时前
WordPress SEO Guide: Boost Rankings Without Technical Jargon
前端·php
日取其半万世不竭18 小时前
CS2 服务器搜不到?GSLT、端口和启动参数逐项检查
运维·服务器·php
360智汇云20 小时前
一次Redis超时引发的“冤案“
数据库·redis·php
ljs64827395120 小时前
Linux 网络常用命令与端口基础详解
linux·网络·php
m0_738120722 天前
PHP代码审计基础——超全局变量(三)
开发语言·安全·网络安全·php