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

admin11652021-08-27

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

1.使用 substr_replace 函数

  1. # substr_replace — 替换字符串的子串

  2. # 使用说明

  3. substr_replace ( mixed $string , mixed $replacement , mixed $start , mixed $length = ? ) : mixed

  4. # $string 资源字符串

  5. # $replacement 替换字符

  6. # $start 替换开始位置,如果位负数的时候,将从末尾开始数

  7. # $length 需要替换的长度,如果为负数的时候,也是从$start开始位置替换

  8. # substr_replace() 在字符串 string 的副本中将由 start 和可选的 length 参数限定的子字符串使用 replacement 进行替换。

  9. # 示例

  10. $mobile = '13312341234';

  11. echo substr_replace($mobile, '****', 3, 4);

  12. // 133****1234

  13. # 注意 字符串的开始位置为0

  14. echo substr_replace($mobile, '****', -8, -4);

  15. // 133****1234

2.使用 正则表达式


  1. # preg_replace — 执行一个正则表达式的搜索和替换

  2. # 使用说明

  3. preg_replace ( mixed $pattern , mixed $replacement , mixed $subject , int $limit = -1 , int &$count = ? ) : mixed

  4. # 搜索 subject 中匹配 pattern 的部分,以 replacement 进行替换。

  5.  

  6. # 示例

  7. $pattern = '/(\d{3})\d{4}(\d{4})/';

  8. $new_mobile = preg_replace($pattern, '$1****$2', $mobile);

  9. echo $new_mobile;


3.使用 substr 函数


  1. # 函数说明

  2. substr ( string $string , int $start , int $length = ? ) : string

  3. # 返回字符串 string 由 start 和 length 参数指定的子字符串。

  4. # 同 substr_replace 一样,start也可以为负数的

  5. # 示例

  6. echo substr($mobile, 0,3) . '****' . substr($mobile, 7,4);

  7. echo substr($mobile, 0,3) . '****' . substr($mobile, -4,4);


网友评论