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"
相关推荐
catchadmin5 小时前
Laravel AI SDK 在 Laracon India 2026 首次亮相
人工智能·php·laravel
云游云记5 小时前
php 高精度数学扩展 bcmath 知识笔记
笔记·php·bcmath
金书世界6 小时前
使用PHP+html+MySQL实现用户的注册和登录(源码)
开发语言·mysql·php
darkb1rd6 小时前
三、PHP字符串处理与编码安全
android·安全·php
toooooop87 小时前
php BC MATH扩展函数巧妙进行财务金额四舍五入
开发语言·php
云游云记21 小时前
PHP 汉字转拼音扩展包:overtrue/pinyin 全面指南
php·overtrue/pinyin
有代理ip1 天前
成功请求的密码:HTTP 2 开头响应码深度解析
java·大数据·python·算法·php
小白学大数据1 天前
实测数据:多进程、多线程、异步协程爬虫速度对比
开发语言·爬虫·python·php
会开花的二叉树1 天前
Reactor网络库的连接管理核心:Connection类
开发语言·网络·php
木子啊1 天前
PHP中间件:ThinkCMF 6.x核心利器解析
开发语言·中间件·php