PHPRegex屏蔽電話號碼中間段

來源:互聯網
上載者:User

標籤:php   如何   Regex   print   運算式   手機   mat   ace   

要屏蔽電話號碼中間段,首先要知道電話號碼的Regex。

先來看看PHP匹配電話號碼的Regex。

匹配固定電話的Regex為:

/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i

匹配手機號碼的Regex為:

/(1[358]{1}[0-9]{9})/i

要用一個運算式來匹配所有的電話號碼只需要將它們合并起來就可以了,如下:

/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)|(1[358]{1}[0-9]{9})/i

例如:

$phone = ‘010-88888888-8‘;
preg_match(‘/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)|(1[358]{1}[0-9]{9})/i‘,$phone,$match);
print_r($match);

看完電話號碼的Regex,再來看如何用星號(*)屏蔽電話號碼中間段。

1、屏蔽手機號碼中間段:

preg_replace(‘/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i‘,‘$1****$2‘,$phone);

2、屏蔽固定電話中間段:

preg_replace(‘/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i‘,‘$1****$2‘,$phone);

例如:

$phone = ‘010-88888888-8‘;
$phone1 = ‘13888888888‘;

$phone = preg_replace(‘/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i‘,‘$1****$2‘,$phone);
$phone1 = preg_replace(‘/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i‘,‘$1****$2‘,$phone1);

echo $phone,‘<br>‘;
echo $phone1,‘<br>‘;

結果輸出:

138****8888
010-8****888

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.