实用讲解PHP隐藏手机号码中间4位方法

首页 编程分享 PHP丨JAVA丨OTHER 正文

藏色散人 转载 编程分享 2021-02-23 23:13:03

简介 今天突然想起手机号,这种隐私信息在项目中还是隐藏一下比较好,所以就来总结一下能用的方法,仅限于大陆的11位手机号...


推荐:《》

方法演示

1.使用 substr_replace函数

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

2.使用正则表达式

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

Id 示例
$pattern = '/(\d{3})\d{4}(\d{4})/';
$new_mobile = preg_replace($pattern, '$1****$2', $mobile);
echo $new_mobile;

3.使用 substr函数

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

总结

方法有很多,多数情况是在情况选择那种更加合适.

转载链接:http://www.php.cn//php-weizijiaocheng-470605.html


Tags:


本篇评论 —— 揽流光,涤眉霜,清露烈酒一口话苍茫。


    声明:参照站内规则,不文明言论将会删除,谢谢合作。


      最新评论




ABOUT ME

Blogger:袅袅牧童 | Arkin

Ido:PHP攻城狮

WeChat:nnmutong

Email:nnmutong@icloud.com

标签云