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"
相关推荐
Flying_Fish_roe7 小时前
linux-网络管理-网络配置
linux·网络·php
Book_熬夜!15 小时前
Python基础(九)——正则表达式
python·正则表达式·php
计算机学姐16 小时前
基于PHP的电脑线上销售系统
开发语言·vscode·后端·mysql·编辑器·php·phpstorm
BLEACH-heiqiyihu16 小时前
红帽9中nginx-源码编译php
运维·nginx·php
翔云API17 小时前
人证合一接口:智能化身份认证的最佳选择
大数据·开发语言·node.js·ocr·php
白总Server17 小时前
MongoDB解说
开发语言·数据库·后端·mongodb·golang·rust·php
fakaifa18 小时前
八戒农场小程序V2最新源码
小程序·uni-app·php·生活·开源软件
吱吱鼠叔19 小时前
MATLAB方程求解:1.线性方程组
开发语言·matlab·php
Messiah___19 小时前
【论文阅读】Slim Fly: A Cost Effective Low-Diameter Network Topology 一种经济高效的小直径网络拓扑
开发语言·php