PHP手機號中間四位用星號*代替顯示的實例
場景
在顯示用戶列表的場景中,一般用到手機號的顯示時都需要對手機號進行處理,一般是把中間的四位換成星號****,
或電商網站,價格中,第2位會用?號替換
實現方法
<?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);
?>
得到
string(11) "123****8910"
string(11) "123****8910"
string(11) "123****8910"
substr_replace函數
定義和用法
substr_replace() 函數把字符串的一部分替換爲另一個字符串。
註釋:如果 start 參數是負數且 length 小於或者等於 start,則 length 爲 0。
註釋:該函數是二進制安全的。
語法
substr_replace(string,replacement,start,length)
參數 | 描述 |
---|---|
string | 必需。規定要檢查的字符串。 |
replacement | 必需。規定要插入的字符串。 |
start | 必需。規定在字符串的何處開始替換。正數 - 在字符串中的指定位置開始替換負數 - 在從字符串結尾的指定位置開始替換0 - 在字符串中的第一個字符處開始替換 |
length | 可選。規定要替換多少個字符。默認是與字符串長度相同。正數 - 被替換的字符串長度 負數 - 表示待替換的子字符串結尾處距離 string 末端的字符個數。0 - 插入而非替換 |
更多實例
例子 1:從第幾位數開始替換
從字符串的第 6 個位置開始替換(把 “world” 替換成 “Shanghai”):
<?php
echo substr_replace("Hello world","Shanghai",6);
?>
例子 2:從末尾開始替換
從字符串結尾的第 5 個位置開始替換(把 “world” 替換成 “Shanghai”):
<?php
echo substr_replace("Hello world","Shanghai",-5);
?>
例子 3:插入開頭的位置
在 “world” 開頭插入 “Hello”:
<?php
echo substr_replace("world","Hello ",0,0);
?>
例子 4:批量替換
一次性替換多個字符串。把每個字符串中的 “AAA” 替換成 “BBB”:
<?php
$replace = array("1: AAA","2: AAA","3: AAA");
echo implode("<br>",substr_replace($replace,'BBB',3,3));
?>