php、js实现手机号中间星号*代替显示
日期:2020-01-15
来源:程序思维浏览:1683次
在php和js前端开发中,我们有时候需要将一个手机号码中的某几位数用星号代替,这样可以保护客户的基本信息,有几种方法:

php方法:
<?php
$tel = '12345678910';
//方法一:字符串截取法
$new_tel1 = substr($tel, 0, 3).'****'.substr($tel, 7);
var_dump($new_tel1);
//方法二:替换字符串的子串
$new_tel2 = substr_replace($tel, '****', 3, 4);
var_dump($new_tel2);
//方法三:用正则
$new_tel3 = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $tel);
var_dump($new_tel3);
?>
结果:
> string(11) "123****8910"
> string(11) "123****8910"
> string(11) "123****8910"
js版本:
如手机号码13123456789,中间四位用'*'代替,
var phone='13123456789'
方法1(字符串的截取):
var showPhone = phone.substr(0,3)+'****'+phone.substr(7);
方法2(正则表达式):
var showPhone = phone.replace(/^(\d{3})\d{4}(\d+)/,"$1****$2")
测试结果: 131****6789

php方法:
<?php
$tel = '12345678910';
//方法一:字符串截取法
$new_tel1 = substr($tel, 0, 3).'****'.substr($tel, 7);
var_dump($new_tel1);
//方法二:替换字符串的子串
$new_tel2 = substr_replace($tel, '****', 3, 4);
var_dump($new_tel2);
//方法三:用正则
$new_tel3 = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $tel);
var_dump($new_tel3);
?>
结果:
> string(11) "123****8910"
> string(11) "123****8910"
> string(11) "123****8910"
js版本:
如手机号码13123456789,中间四位用'*'代替,
var phone='13123456789'
方法1(字符串的截取):
var showPhone = phone.substr(0,3)+'****'+phone.substr(7);
方法2(正则表达式):
var showPhone = phone.replace(/^(\d{3})\d{4}(\d+)/,"$1****$2")
测试结果: 131****6789
精品好课