三种方法实现PHP隐藏手机号码中间4位(仅限大陆手机号)

    选择打赏方式

写在前面:因为全球各地的手机号规则五花八门,无法做到全部都通用,本文教程仅限于大陆的11位手机号,如需其他国家地区支持自行修改代码即可

1.使用 substr_replace 函数

# substr_replace — 替换字符串的子串
# 使用说明
substr_replace ( mixed $string , mixed $replacement , mixed $start , mixed $length = ? ) : mixed
# $string 资源字符串
# $replacement 替换字符
# $start 替换开始位置,如果位负数的时候,将从末尾开始数
# $length 需要替换的长度,如果为负数的时候,也是从$start开始位置替换
# substr_replace() 在字符串 string 的副本中将由 start 和可选的 length 参数限定的子字符串使用 replacement 进行替换。
# 示例
$mobile = '13312341234';
echo substr_replace($mobile, '****', 3, 4);
// 133****1234
# 注意 字符串的开始位置为0
echo substr_replace($mobile, '****', -8, -4); 
// 133****1234
2.使用 正则表达式

# preg_replace — 执行一个正则表达式的搜索和替换
# 使用说明
preg_replace ( mixed $pattern , mixed $replacement , mixed $subject , int $limit = -1 , int &$count = ? ) : mixed
# 搜索 subject 中匹配 pattern 的部分,以 replacement 进行替换。

# 示例
$pattern = '/(\d{3})\d{4}(\d{4})/';
$new_mobile = preg_replace($pattern, '$1****$2', $mobile);
echo $new_mobile;
3.使用 substr 函数

# 函数说明
substr ( string $string , int $start , int $length = ? ) : string
# 返回字符串 string 由 start 和 length 参数指定的子字符串。
# 同 substr_replace 一样,start也可以为负数的
# 示例
echo substr($mobile, 0,3) . '****' . substr($mobile, 7,4);
echo substr($mobile, 0,3) . '****' . substr($mobile, -4,4);

版权声明:若无特殊注明,本文为《傲世》原创,转载请保留文章出处。
本文链接:https://www.recho.cn/192.html
正文到此结束

热门推荐

发表吐槽

匿名评论 请叫我雷锋~

你还可以输入 250 / 250 个字

呵呵 哈哈 吐舌 开心 笑眼 可怜 乖 啊 你懂得 不高兴 生气 汗 黑线 哭 真棒 阴险 鄙视 酷 滑稽 纳尼 疑问 委屈 惊讶 勉强

评论信息框
可使用QQ号实时获取头像自动填写

私密评论

吃奶的力气提交吐槽中...


竟然没有人吐槽,快赶紧抢沙发吧!