在一些特定的场景中,一般用到手机号的显示时都需要对手机号进行处理,一般是把中间的四位换成星号****,老猫我本人用php处理的思路是进行替换,用****替换手机号的中间四位,代码如下:
$all_lottery_logs = ********; //该语句是得到中奖纪录
//遍历处理手机号
foreach($all_lottery_logs as $k=>$v){
$xing = substr($v['tel'],3,4); //获取手机号中间四位
$all_lottery_logs[$k]['tel'] = str_replace($xing,'****',$v['tel']); //用****进行替换
}
另外几种方法:
<?php
$tel = '12345678910';
//1.字符串截取法
$new_tel1 = substr($tel, 0, 3).'****'.substr($tel, 7);
var_dump($new_tel1);
//2.替换字符串的子串
$new_tel2 = substr_replace($tel, '****', 3, 4);
var_dump($new_tel2);
//3.用正则
$new_tel3 = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $tel);
var_dump($new_tel3);
?>
PHP函数:
//$phone 代表手机号
function hidtel($phone){
$IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i',$phone);
if($IsWhat == 1){
return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i','$1****$2',$phone);
}else{
return preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);
}
}
结果显示:
> string(11) "123****8910"
> string(11) "123****8910"
> string(11) "123****8910"
希望能给大家带来帮助